在 ReactJS 中获取表单数据 [英] Get form data in ReactJS
问题描述
我的 render
函数中有一个简单的表单,如下所示:
I have a simple form in my render
function, like so:
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
},
handleLogin: function() {
//How to access email and password here ?
}
我应该在我的 handleLogin: function() { ... }
中写什么来访问 Email
和 Password
字段?
What should I write in my handleLogin: function() { ... }
to access Email
and Password
fields?
推荐答案
在输入上使用 change
事件来更新组件的状态并在 handleLogin
中访问它:
Use the change
events on the inputs to update the component's state and access it in handleLogin
:
handleEmailChange: function(e) {
this.setState({email: e.target.value});
},
handlePasswordChange: function(e) {
this.setState({password: e.target.value});
},
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} />
<input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/>
<button type="button" onClick={this.handleLogin}>Login</button>
</form>);
},
handleLogin: function() {
console.log("EMail: " + this.state.email);
console.log("Password: " + this.state.password);
}
工作 fiddle.
另外,阅读文档,有一整节专门用于表单处理:表单
Also, read the docs, there is a whole section dedicated to form handling: Forms
以前你也可以使用 React 的双向数据绑定助手 mixin 来实现同样的事情,但现在不推荐使用它来支持设置值和更改处理程序(如上):
Previously you could also use React's two-way databinding helper mixin to achieve the same thing, but now it's deprecated in favor of setting the value and change handler (as above):
var ExampleForm = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {email: '', password: ''};
},
handleLogin: function() {
console.log("EMail: " + this.state.email);
console.log("Password: " + this.state.password);
},
render: function() {
return (
<form>
<input type="text" valueLink={this.linkState('email')} />
<input type="password" valueLink={this.linkState('password')} />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
}
});
文档在这里:双向绑定助手.
这篇关于在 ReactJS 中获取表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!