ReactJs: refs 未定义 (no-undef)

我已经阅读了 Refs 和 Dom,并尝试搜索可能与我的问题相关的任何问题或答案(我从“函数”而不是“类”开始)。


这是问题名称:'refs' 未定义 (no-undef) (at console.log(refs.okanhzai.value);)


这是我的代码:


function ok123(){


      console.log(refs.okanhzai.value);

     }

<div className="panel panel-default">

  <div className="panel-heading">

    <h3 className="panel-title">Categories ok man</h3>

  </div>

  <div className="panel-body">

<div className="form-group">

  

              <label >Search for it</label>


<input type="text" className="form-control" ref="okanhzai"/>


  </div> 


  <button type="submit" className="btn btn-primary" onClick = { ok123() }> Save </button>  

我正在尝试将我的输入值打印到控制台。如果我的代码有任何潜在的错误或错误,请至少帮我指出。我将不胜感激任何进一步的帮助。^_^。谢谢!


隔江千里
浏览 49回答 1
1回答

HUH函数

我认为应该首先将 html 包装为 React 组件。然后你就可以开始使用 ref 属性了。在下面的代码中,我将您的代码包装成一个函数组件,并使用 React.createRef() 创建一个 ref 并分配给 okanhzai。okanhzai.current.value 存储当前输入。const App = () => {&nbsp; const okanhzai = React.createRef(null);&nbsp; function ok123(){&nbsp; &nbsp; console.log(okanhzai.current.value);&nbsp; }&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div className="panel panel-default">&nbsp; &nbsp; &nbsp; &nbsp; <div className="panel-heading">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h3 className="panel-title">Categories ok man</h3>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div className="panel-body">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className="form-group">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label >Search for it</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" className="form-control" ref={okanhzai}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <button type="submit" className="btn btn-primary" onClick={ok123}> Save </button>&nbsp; &nbsp; </div>&nbsp; )}const container = document.querySelector('#root');ReactDOM.render(<App />, container);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="root"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript