繁体   English   中英

React Form onChange不会更新状态

[英]React Form onChange doesn't update state

输入密码<input/>时出现奇怪的行为。 每次我向其中输入内容时,状态都不会改变,但会变为console.logs。 电子邮件字段不会发生同样的事情,当我尝试提交表单时,密码为空...我在做什么错?

这是我的反应成分:

  5 export default class Login extends React.Component {
  6   state: {
  7     email: string,
  8     password: string,
  9   };
 10
 11   handleEmailChange: (e: any) => void;
 12   handlePasswordChange: (e: any) => void;
 13   handleButtonPress: () => void;
 14
 15   constructor() {
 16     super();
 17     this.state = { email: '', password: '' };
 18
 19     this.handleEmailChange = this.handleEmailChange.bind(this);
 20     this.handlePasswordChange = this.handleButtonPress.bind(this);
 21     this.handleButtonPress = this.handleButtonPress.bind(this);
 22   };
 23
 24   handleEmailChange(e: any) {
 25     this.setState({ email: e.target.value });
 26   };
 27
 28   handlePasswordChange(e: any) {
 29     this.setState({ password: e.target.value });
 30   };
 31
 32   handleButtonPress() {
 33     axios.post('/api/users/login', {
 34       email: this.state.email,
 35       password: this.state.password,
 36     })
 37     .then((response: any) => {
 38       console.log(response.data);
 39     })
 40     .catch((error: any) => {
 41       console.log(error);
 42     });
 43   };
 44
 45   render() {
 46     return (
 47       <div>
 48         <input
 49           type="email"
 50           onChange={this.handleEmailChange}
 51           placeholder="Enter email"
 52         />
 53         <input
 54           type="password"
 55           onChange={this.handlePasswordChange}
 56           placeholder="Enter password"
 57         />
 58         <button onClick={this.handleButtonPress}>
 59           Login!
 60         </button>
 61       </div>
 62     );
 63   }
 64 }

这是我输入密码时发生的屏幕截图: 在此处输入图片说明

先感谢您。

第20行出现错误。

this.handlePasswordChange = this.handleButtonPress.bind(this);

它应该是

this.handlePasswordChange = this.handlePasswordChange.bind(this);

边注:

使用ES6,您可以将handleEmailChangehandlePasswordChange重构/组合为:

handleChange = (e) => {
 this.setState({
   [e.target.name]:e.target.value 
 });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM