在类组件中绑定反应实例方法

时间:2017-03-07 00:47:21

标签: javascript reactjs ecmascript-6

我刚刚开始使用ES6和React,我想在我的组件类中创建一个验证方法,以便在继续之前进行验证。

## if your data is in a data frame you can do it like this 
your_data = zoo::na.locf(your_data, fromLast = TRUE)

## if your data is a list, do this
your_data = lapply(your_data, zoo::na.locf, fromLast = TRUE)

在反应组件中绑定实例方法与事件处理程序有什么不同吗?我有一个setUser方法,我传递给正确调用的子组件。但是当我尝试从loginUser eventHandler中调用class LoginPage extends React.Component { constructor(props) { super(props); this.setUser = this.setUser.bind(this); this.isFormValid = this.isFormValid.bind(this); this.state = { user: { username: '', password: '' } }; } isFormValid() { console.log("is valid"); let isValid = true; let errors = {}; if (this.state.user.username.length <= 0) { errors.username = "Username cannot be blank"; isValid = false; } if (this.state.user.password.length <= 0) { errors.password = "Password cannot be blank"; isValid = false; } this.setState({ errors: errors }); return isValid; } setUser(event) { let username = event.target.username; let password = event.target.password; this.setState({ user: { username: username, password: password }, errors: {} }); } loginUser(event) { event.preventDefault(); if (!this.isFormValid()) { return; } } render() { return ( <LoginForm user={this.state.user} onChange={this.setUser} onLogin={this.loginUser} /> ); } 时,我得到了

isFormValid

1 个答案:

答案 0 :(得分:2)

消息Cannot read property 'isFormValid' of null表示正在从null对象访问isFormValid。 含义,this方法中的loginUser为空。 因此绑定在构造函数中调用isFormValid的方法,即loginUser

constructor(props) {
  super(props);
  /// other methods
  this.loginUser = this.loginUser.bind(this);
}