【问题标题】:React Native: bind and 'this'?React Native:绑定和'this'?
【发布时间】:2018-01-10 16:48:08
【问题描述】:
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)}

正如您在最后一行代码中看到的,每当我的按钮被按下时,我的按钮都会调用 onButtonPress 函数。我还使用 .bind(this) 使方法绑定到 LoginForm 组件。因为据我所知,ES6 类不会自动将方法绑定到自身。但是,如果我写了 this.onButtonPress,方法 onButtonPress() 中的“this”指的是什么 而不是 this.onButtonPress.bind(this) 为什么?

【问题讨论】:

    标签: reactjs this bind


    【解决方案1】:

    传递给bind的第一个参数将定义绑定函数内this的值。

    在您的情况下,您传递“this”(而不是“foo”或“bar”),因为您希望来自 onButtonPressthis 成为您的 renderthis,这是你的LoginForm 班级。

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

    【讨论】:

    • 我认为问题是如果代码不使用.bind(),上下文(this)在onButtonPress() 中会是什么。
    • 那么它将是undefined。因为onButtonPress 不会引用它的类。
    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2020-01-15
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多