Reactjs which is the better way to use change handler

心已入冬 提交于 2020-01-05 00:53:52

问题


So I know there are several ways to do this but I am wondering which is the better or more appropriate way to create a search bar component? Could you please explain why? I'm new to react and have seen tutorials and what not and everybody does there change handlers a little differently.

state = {
 term: '',
};

onChange = this.onChange.bind(this);

onChange(e) {
 console.log(e.target.value);
 this.setState({ term: e.target.value });
};

<input
 value={this.state.term}
 onChange={this.onChange}
/>

I feel this way could be better because it allows you to reuse the onChange handler for several different states.

state = {
 term: '',
};

onChange = name => e => {
 this.setState({ [name]: e.target.value });
};

<input
 value={this.state.term}
 onChange={this.onChange('term')}
/>

回答1:


In order to reuse the onChange handler, the below code would be more appropriate and better too.

onChange = e => {
 this.setState({ 
    [e.target.name]: e.target.value 
 });
};

<input type="text" name="name" onChange={(e)=>this.onChange(e)} />


来源:https://stackoverflow.com/questions/51683504/reactjs-which-is-the-better-way-to-use-change-handler

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