我正在使用一个简单的登录表单,我有LoginContainer(容器组件)和登录(演示组件),我正在尝试提交表单并访问容器组件中的数据。
这是我的代码
Login.js:
export default class Login extends React.Component {
constructor() {
super();
}
render() {
return (
<div className="login jumbotron center-block">
<h1>Login</h1>
<form role="form">
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" ref="username" placeholder="Username" />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" ref="password" placeholder="Password" />
</div>
<div className="form-group">
<button type="submit" className="btn btn-default" onClick={()=>{this.props.login(this.refs.username,this.refs.password)}}>Submit</button>
</div>
</form>
</div>
);
}
}
容器组件是:
class LoginContainer extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<Login login={this.loginUser}/>
</div>
);
}
}
function mapStateToProps(state){
return state;
}
function mapDispatchToProps(dispatch){
return{
login : (username,password) => {
console.log('mapDispatchToProps : username=['+username+'] password=['+password+']');
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(LoginContainer);
上面的代码不能像提交的事件处理程序那样工作,我无法访问this.refs
Uncaught ReferenceError: refs is not defined
我不想保持登录组件的状态。我可以在Login中轻松地使用用户名和密码创建状态,并使用onclick或onchange在用户名和密码控件上使用setState。
有没有办法可以使用表单提交将表单元素的数据从Presentation组件发送到Container组件?
由于
答案 0 :(得分:1)
您需要在Login.js文件中创建事件处理方法,并使用构造函数中的bind函数将它们绑定到组件上下文。
export default class Login extends React.Component {
constructor() {
super();
this.login = this.login.bind(this);
}
login() {
this.props.login(this.refs.username,this.refs.password)
}
render() {
return (
<div className="login jumbotron center-block">
<h1>Login</h1>
<form role="form">
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" ref="username" placeholder="Username" />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" ref="password" placeholder="Password" />
</div>
<div className="form-group">
<button type="submit" className="btn btn-default" onClick={this.login}>Submit</button>
</div>
</form>
</div>
);
}
}
这样你就不会维护逻辑组件的状态,只需使用从容器传递的道具。