将 Input 的值传递给 handleMethod

任务是将输入的每个字符传递给handleExchange方法。在此方法中,将发生对输入值的处理。


如何将输入标签传递给handleExchange方法的参数?


function App() {


    function handleExchange(value) {

      console.log(value)

    }


    return (

      <input className = "input-r" placeholder = "Type here" />

    )



}


ReactDOM.render(<App /> , document.getElementById('root'));

<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>

我试图这样做:

function App() {

  function handleExchange(value) {

    console.log(value);

  }

  

  return (

    <div>

      <input className="input-r" placeholder="Type here" onKeyPress={handleExchange(this.value)} /> 

      {/*or*/}

      {/* onKeyPress={handleExchange(event) */}

    </div>

  )


}


ReactDOM.render(<App />, document.getElementById("root"))

<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>


芜湖不芜
浏览 170回答 2
2回答

慕的地6264312

您必须使用onChangeevent 并从event.target.你有例子:function App() {&nbsp; function handleExchange(e) {&nbsp; &nbsp; console.log(e.target.value);&nbsp; }&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <input className="input-r" placeholder="Type here" onChange={handleExchange} />&nbsp;&nbsp; &nbsp; &nbsp; {/*or*/}&nbsp; &nbsp; &nbsp; {/* onKeyPress={handleExchange(event) */}&nbsp; &nbsp; </div>&nbsp; )}ReactDOM.render(<App />, document.getElementById("root"))<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>

幕布斯7119047

onChange向input元素添加处理程序。注意:处理程序传递 ,event因此您需要从事件目标中获取值。在这里,我使用了destructuring。function App() {&nbsp; &nbsp; function handleExchange(e) {&nbsp; &nbsp; &nbsp; const { target: { value } } = e;&nbsp; &nbsp; &nbsp; console.log(value)&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; className="input-r"&nbsp; &nbsp; &nbsp; &nbsp; placeholder="Type here"&nbsp; &nbsp; &nbsp; &nbsp; onChange={handleExchange}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; );}ReactDOM.render(<App /> , document.getElementById('root'));<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