有没有比 onChange 更简洁的方法将输入字段连接到 React 中的状态属性? [英] Is there a neater way to connect an input field to a state property in React than onChange?
问题描述
请看下面的代码作为我们的示例,输入字段上的简单 2 向数据绑定将该字段连接到属性 inputValue
.
So look at this code below for our example, a simple 2-way data-binding on an input field connecting the field to a property inputValue
.
但是假设您有一个包含 30 个或更多输入的更复杂的页面.您是否应该在类中编写 30 多个 onChange
处理程序,所有这些处理程序都具有与 onNameChange
、onEmailChange
、 等输入相对应的不同名称onPhoneChange
等等?没有比我在下面提供的更简洁、更隐式的输入绑定方式了吗?
But say you have a more complex page with 30 or more inputs. Are you supposed to write 30+ onChange
handlers in the class, all with different names corresponding to the inputs like onNameChange
, onEmailChange
, onPhoneChange
, and so on? Is there no neater, more implicit way to bind inputs than what I have below here?
React.createClass({
getInitialState() {
inputValue: ''
},
render() {
return (
<input
type='text'
value={this.state.inputValue}
onChange={this.onChange} />
);
},
onChange(e) {
this.setState({ inputValue: e.target.value });
}
});
我想我可以这样做并避免在类上编写处理程序:
I suppose I could do this and avoid writing handlers on the class:
<input onChange={ e => this.setState({firstName: e.target.value}) } />
那是犹太洁食吗?
推荐答案
React docs 有你的解决方案:
React docs has your solution:
https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
this.setState({
[target.name]: target.value
});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} />
</label>
<label>
Email:
<input name="email" type="text" value={this.state.email} onChange={this.handleInputChange} />
</label>
<label>
Pet:
<input name="country" type="text" value={this.state.country} onChange={this.handleInputChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
这篇关于有没有比 onChange 更简洁的方法将输入字段连接到 React 中的状态属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!