this.state is undefined during onPress event in react native

后端 未结 1 658
天命终不由人
天命终不由人 2021-02-14 04:16

Hello i new in react native, my code is:



        
1条回答
  •  遥遥无期
    2021-02-14 04:46

    This is a binding issue. The simplest solution will be to change your JSX for the button tag like so:

    ES6 classes lose the autobinding you may have been used to with es5 react.createClass. You have to be more conscious of your binding when using ES6 for react components.

    Another option is to bind the method in your constructor like so:

      constructor(props) {
        super(props);
        this.state = {
          email: '',
          password: ''
        };
    
        this.onPress = this.onPress.bind(this)
      }
    

    Or you could even utilize a fat arrow es6 syntax function to maintain the 'this' binding to the component you're creating:

    UPDATE:

    To update this again, if your environment supports some ES7 features (which I believe react-native built from react-native init or create-react-native-app shoudl do) you can use this notation to auto-bind your class methods that utilize the this keyword.

    // This is auto-bound so `this` is what you'd expect
    onPress = () => {
        console.log(this.state.email);
    };
    

    instead of

    // This is not auto-bound so `this.state` will be `undefined`
    onPress(){
      console.log(this.state.email);
    }
    

    The best options are to use the ES7 feature if available or to bind in your constructor. Using an anonymous function onPress={() => this.onPress()} or onPress={this.onPress.bind(this)} directly on your Button is much less favorable for performance reasons.

    0 讨论(0)
提交回复
热议问题