React:事件处理程序中为null [英] React: this is null in event handler
本文介绍了React:事件处理程序中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个LoginForm组件.我想在提交之前检查是否同时设置了 loginName
和 password
.我尝试使用此代码(省略了很多东西):
I have a LoginForm component. I want to check before submit, that both loginName
and password
is set. I tried with this code (a lot of stuff omitted):
class LoginForm extends Component {
constructor() {
super();
this.state = {
error: "",
loginName: "",
password: "",
remember: true
};
}
submit(e) {
e.preventDefault();
if(!this.state.loginName || !this.state.password) { //this is null
this.setState({ error: "Fill in both fields" });
} else {
console.log("submitting form");
}
}
render() {
return (
<div className="col-xs-12 col-sm-6 col-md-4">
<form className="login" onSubmit={this.submit}>
<button type="submit" className="btn btn-default">Sign in</button>
</form>
</div>
);
}
}
export default LoginForm;
但是,我在事件处理程序中收到了 TypeError
,说 this
为空.
however, i get a TypeError
in the event handler, saying that this
is null.
我该怎么办?
推荐答案
您需要为 submit
方法设置 this
,因为现在 this
是 undefined
,对于此操作,您可以使用 .bind
You need set this
for submit
method because now this
is undefined
, for this operation you can use .bind
onSubmit={ this.submit.bind(this) }
,或者您可以使用箭头功能
onSubmit={ (e) => this.submit(e) }
这篇关于React:事件处理程序中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文