Material-ui 在表单组件中设置状态值不起作用
Material-ui setting state values in form component not working
我正在尝试使用 Material-ui 创建一个新的登录组件。我有两个状态变量 'username' 和 'password'。当我填写文本字段并提交时,状态值在我的 submitForm 函数中不可用。
我的代码是:
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
submitForm(e) {
e.preventDefault();
console.log('test');
console.log(this.state.username.trim());
console.log(this.state.password.trim());
};
render() {
return (
<form className="commentForm">
<TextField
value={this.state.username}
onChange={e => this.setState({ username: e.target.value })}
hintText = "username" style={textfieldStyles.margin}
/>
<TextField
value={this.state.password}
onChange={e => this.setState({ password: e.target.value })}
hintText = "password" type="password"
/>
<IconButton iconStyle={{iconHoverColor: '#55ff55'}}
tooltip="Sing In" key='signin-button'
// onTouchTap={this.handleTouchTap}
onClick={this.submitForm}
>
<ArrowIcon color={Colors.cyan500} style={{marginTop: 30}} hoverColor={hoverColor} />
</IconButton>
</form>
);
}
}
export default Login;
控制台输出console.log('test');正在工作,但
console.log(this.state.username.trim());
console.log(this.state.password.trim());
没有给出任何输出。
我是不是漏掉了设置状态变量的东西?或者我需要包括其他东西才能使其正常工作?
因为您使用的是 ES6 class 语法,所以您应该为 class 方法绑定 this
,在本例中是 submitForm
方法。
https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
...
}
否则您将无法访问 submitForm
内的 this.state
。
我正在尝试使用 Material-ui 创建一个新的登录组件。我有两个状态变量 'username' 和 'password'。当我填写文本字段并提交时,状态值在我的 submitForm 函数中不可用。
我的代码是:
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
submitForm(e) {
e.preventDefault();
console.log('test');
console.log(this.state.username.trim());
console.log(this.state.password.trim());
};
render() {
return (
<form className="commentForm">
<TextField
value={this.state.username}
onChange={e => this.setState({ username: e.target.value })}
hintText = "username" style={textfieldStyles.margin}
/>
<TextField
value={this.state.password}
onChange={e => this.setState({ password: e.target.value })}
hintText = "password" type="password"
/>
<IconButton iconStyle={{iconHoverColor: '#55ff55'}}
tooltip="Sing In" key='signin-button'
// onTouchTap={this.handleTouchTap}
onClick={this.submitForm}
>
<ArrowIcon color={Colors.cyan500} style={{marginTop: 30}} hoverColor={hoverColor} />
</IconButton>
</form>
);
}
}
export default Login;
控制台输出console.log('test');正在工作,但
console.log(this.state.username.trim());
console.log(this.state.password.trim());
没有给出任何输出。
我是不是漏掉了设置状态变量的东西?或者我需要包括其他东西才能使其正常工作?
因为您使用的是 ES6 class 语法,所以您应该为 class 方法绑定 this
,在本例中是 submitForm
方法。
https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
...
}
否则您将无法访问 submitForm
内的 this.state
。