React Native: bind and 'this'?

泪湿孤枕 提交于 2019-12-11 15:30:02

问题


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



来源:https://stackoverflow.com/questions/48192280/react-native-bind-and-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!