当我输入密码<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 }
提前谢谢。
答案 0 :(得分:1)
错误。
this.handlePasswordChange = this.handleButtonPress.bind(this);
应该是
this.handlePasswordChange = this.handlePasswordChange.bind(this);
答案 1 :(得分:0)
旁注:
使用ES6您可以重构/合并 handleEmailChange 和 handlePasswordChange 进入:
handleChange = (e) => {
this.setState({
[e.target.name]:e.target.value
});
}