我的render函数中有一个简单的形式,如下所示:
render
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字段中写什么?
handleLogin: function() { ... }
Email
Password
使用change输入上的事件来更新组件的状态并在以下位置访问它handleLogin:
change
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); }
工作小提琴。
以前你也可以使用 React 的双向数据绑定助手 mixin 来实现同样的事情,但现在它已被弃用,有利于设置值和更改处理程序(如上):
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> ); } });