React- Cannot read property 'setState' of undefined

前端 未结 3 1025
野的像风
野的像风 2021-02-14 08:11

for some reason, I\'m getting the error \" React- Cannot read property \'setState\' of undefined\". So this.state is never getting updated with the values that the user inputs.

3条回答
  •  情深已故
    2021-02-14 08:58

    In these event handlers, e.target is the which triggered the event.

    onChangeName(e) {
        //this.state.name = e.target.name
        this.setState({ name: e.target.name});
    }
    
    onChangePassword(e) {
        //this.state.password = e.target.name
        this.setState({ password: e.target.password });
    }
    

    You get an input's value by using its value property:

    onChangeName(e) {
        this.setState({name: e.target.value});
    }
    
    onChangePassword(e) {
        this.setState({password: e.target.value});
    }
    

    You also need to ensure this is bound properly, as per the commented-out code in your constructor.


    If you give your inputs suitable name props, you replace these with a single onChange handler:

    constructor(props) {
      super(props)
      // ...
      this.onChange = this.onChange.bind(this)
    }
    
    onChange(e) {
      this.setState([e.target.name]: e.target.value})
    }
    
    render() {
      // ...
      
      
      // ...
    }
    

提交回复
热议问题