【发布时间】:2017-01-06 11:47:27
【问题描述】:
我有一个表单,如何在handleSubmit()方法中获取使用输入?
handleSubmit(e) {
e.preventDefault()
//how to get the user input?
}
render() {
return (
<div className="col-sm-4">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="user"/>
<input type="text" placeholder="comments"/>
<input type="submit" hidden/>
</form>
</div>
)
}
到目前为止,我知道三种解决方案:
第一个,使用refs,但是我看到很多人说我们应该避免使用它
第二个,每个<input>加onChange(),例如
class Example extends React.Component {
state = {
inputValue: ""
};
handleInputChanged(e) {
this.setState({
inputValue: e.target.value
});
}
render() {
return (
<div>
<input onChange={this.handleInputChanged.bind(this)} value={this.state.inputValue}>
</div>
);
}
}
这个很好,有几个输入。但是如果表单有 20 个输入字段,那么有 20 种不同的 onChange 方法呢?
第三,使用一些 npm 模块,比如redux-form。
还有什么建议吗?谢谢
【问题讨论】: