任务是将输入的每个字符传递给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>

最佳答案

您必须使用onChange事件并从event.target获取值。

那里有例子:



function App() {
  function handleExchange(e) {
    console.log(e.target.value);
  }

  return (
    <div>
      <input className="input-r" placeholder="Type here" onChange={handleExchange} />
      {/*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>

关于javascript - 将Input的值传递给handleMethod,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58799657/

10-11 23:31