如何通过 React hooks onChange 事件方法传递附加参数

我需要输出修改后的值。假设我正在输入:hello world,我需要这个结果:“hello world”(带引号)。我可以用 class-component 来做,但我用 Hooks 失败了。我的代码有什么问题?


const { useState } = React;


const App = () => {

  const [user, setUser] = useState('');


  const onChange = (a, b, event) => {

    setUser(a + event.target.value + b);

  };


  return (

    <form>

      <h3>Username is: {user}</h3>

      <input

        type="text"

        value={user}

        onChange={onChange.bind(null, '"', '"')} />

    </form>

  );

};


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

<div id="root"></div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>


芜湖不芜
浏览 143回答 3
3回答

牛魔王的故事

问题由于onChange在每次按键时运行,因此您将quotation标记附加到每个按键。解决方案而不是把你的引号放在你的状态上。在 JSX 中附加引号。import React, { useState } from 'react';const App = () => {&nbsp; const [user, setUser] = useState('');&nbsp; const onChange = (event) => {&nbsp; &nbsp; setUser(event.target.value)&nbsp; };&nbsp; return (&nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; <h3>Username is: {user ? `"${user}"`: ''}</h3>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; value={user}&nbsp; &nbsp; &nbsp; &nbsp; onChange={onChange} />&nbsp; &nbsp; </form>&nbsp; );};export default App;从输入字段传递额外参数<input&nbsp; &nbsp;onChange={e => onChange(e, 'hello, 'world')}/>

手掌心

When you use arrow functions there is no need to bind.&nbsp;&nbsp;const&nbsp; &nbsp;onChange = (val)=>{&nbsp; &nbsp; console.log(val)// comment&nbsp; &nbsp; }&nbsp; &nbsp; <input type="text"&nbsp; &nbsp; &nbsp; &nbsp;onChange={() => onChange("comment")}&nbsp; &nbsp; />

慕斯王

我使用 coffeescript,你可以将 -> 视为函数或 =>,如果我们通过循环将参数传递给功能组件中的 onClick 事件处理程序:onClick = (n, x) -> ->&nbsp; &nbsp; setcheckindex n&nbsp; &nbsp; x()<Boxr onClick={onClick n, x.onClick} /> for x,n in g我已经通过 n 发送了循环索引,并通过 x.onClick 发送了一个函数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript