How can I have only one onChange for several inputs in reacthooks?

早过忘川 提交于 2021-01-28 13:19:10

问题


in react.js i add a name attribute to each element For example:

   handleChange1(event) {
        const {name, value} = event.target
        this.setState({[name]: value});
    }
    <input name="inputone" type="text" value={this.state.value1} onChange={this.handleChange1} />

But how do I do that in react-hook? for example:

           <Input
                      name="FirstName"
                      onChange={onChangeFirstName}    
                    ></Input>
const onChangeFirstName = (event) => {
    setFirstName(event.target.value);
  };

In fact, my question is, if I have multiple inputs, how can I write a handleChange for them?


回答1:


I did ask similar question a month ago, about using hooks with multiple state, with one onChangeHandler using hooks:

const [name, setName] = useState({
  firstName: '',
  middleName: '',
  lastName: '',
})

const onChangeHandler = (event) => {
 const {name, value} = event.target;

 setName({
   ...name,
   [name]: value,
 })
}

return(
  <div>
    <input
     type="text"
     name="fistName"
     value={firstNmae}
     onChange={onChangeHandler}
    />
  </div>
)


来源:https://stackoverflow.com/questions/64413135/how-can-i-have-only-one-onchange-for-several-inputs-in-reacthooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!