0
我剛剛開始使用ES6和React,並且希望在繼續之前在我的組件類中創建一個驗證方法以進行驗證。在類組件中綁定反應實例方法
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} />
);
}
反應組件中的綁定實例方法比事件處理程序有什麼不同嗎?我有一個setUser方法,傳遞給正確調用的子組件。但是,當我嘗試調用isFormValid
從loginUser事件處理程序中,我得到
Uncaught TypeError: Cannot read property 'isFormValid' of null
您需要綁定您的組件的這個 – Li357
你必須做同樣的事情在構造函數中'loginUser'你正在做'setUser'(即把它綁定)。 'isFormValid'實際上並不需要綁定。我建議審查爲什麼綁定是必要的,以便您知道它實際上做了什麼以及什麼時候有必要。 –