ReactJS是使用变更处理程序的更好方法 [英] Reactjs which is the better way to use change handler

查看:82
本文介绍了ReactJS是使用变更处理程序的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道有几种方法可以做到这一点,但我想知道哪种更好或更合适的方法来创建搜索栏组件?你能解释为什么吗?我是新来的反应者,看过教程,但是没有,每个人所做的更改处理程序都有些不同.

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}
/>

我觉得这种方法可能更好,因为它允许您将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')}
/>

推荐答案

为了重用onChange处理程序,下面的代码也将更合适也更好.

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)} />

这篇关于ReactJS是使用变更处理程序的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆