React Native: bind and 'this'?

2019-08-16 12:42发布

问题:

class LoginForm extends Component {
  state = { email: '', password: '', alert: 'Please Enter Your Email And Password' }


  onButtonPress() {
    const { email, password } = this.state;

    this.setState({ alert: 'Please Try Again' });

    firebase.auth().signInWithEmailAndPassword(email, password)
      .catch(() => {
        firebase.auth().createUserWithEmailAndPassword(email, password)
          .catch(() => {
            this.setState({ alert: 'Login/Registeration Failed.' });
          });
      });
  }

  render() {
    return (
      <Card>
        <CardSection>
          <Button
            text={'Login'}
            onPress={this.onButtonPress.bind(this)}

As you see in the last line of code, my button calls the function onButtonPress whenever my button is pressed. I also used .bind(this) to make the method bounded to the LoginForm component. Because as far as I know ES6 classes do not auto-bind methods to itself. But what does 'this' in the method onButtonPress() refer to if I wrote this.onButtonPress instead of this.onButtonPress.bind(this) and why?

回答1:

The first parameter passed to bind will define the value of this inside the bound function.

In your case you pass "this" (and not "foo" or "bar") because you want the this from onButtonPress to be the this of your render, which is the instance of your LoginForm class.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind