将Input的值传递给handleMethod

时间:2019-11-11 10:31:14

标签: javascript html reactjs

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

2 个答案:

答案 0 :(得分:1)

您必须使用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>

答案 1 :(得分:0)

input元素添加onChange处理程序。注意:处理程序传递了event,因此您需要从事件目标中获取值。在这里,我使用了destructuring

function App() {

    function handleExchange(e) {
      const { target: { value } } = e;
      console.log(value)
    }

    return (
      <input
        className="input-r"
        placeholder="Type here"
        onChange={handleExchange}
      />
    );

}

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>