简体   繁体   中英

Why is my binding in constructor not working?

In my react native app I have a function for when the user presses a button (handleButtonAPressed) which uses setState, so I am trying to bind it in my constructor with the following code

const handleButtonAPressed = () => {
  this.setState({x: this.state.x + 1});
}

export default class SvgExample extends React.Component {

  constructor(props) {
    super(props);
    this.state = { x: 0, y: 0 };
    this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
  }

  render() {
    return (
      <View>
        <RoundButton onPress={handleButtonAPressed} />
      </View>
    );
  }
}

However, I am getting the error:

'TypeError: undefined is not an object (evaluating '_this2.handleButtonAPressed.bind)

handleButtonAPressed should be inside your class so you can do this.handleButtonAPressed.bind(this) . If you don't have handleButtonAPressed inside you class, this.handleButtonAPressed will be undefined and impossible to do .bind .

Here is what you should do

export default class SvgExample extends React.Component {

  constructor(props) {
    super(props);
    this.state = { x: 0, y: 0 };
    this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
  }

  handleButtonAPressed() {
    this.setState({x: this.state.x + 1});
  }

  render() {
    return (
      <View>
        <RoundButton onPress={handleButtonAPressed} />
      </View>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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