[英]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,您可以將handleEmailChange和handlePasswordChange重構/組合為:
handleChange = (e) => {
this.setState({
[e.target.name]:e.target.value
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.