【问题标题】:this.props undefined in class methodthis.props 在类方法中未定义
【发布时间】:2019-03-03 13:32:50
【问题描述】:

我有一个带有renderonPress 方法的组件,如下所述...

  onCardPressed(event) {
    console.log(this.props);
    const { data } = this.props;
    console.log(event, data);
  }

  render() {
    const { data } = this.props;
    return (
      <TouchableOpacity
        onPress={this.onCardPressed}
      >
        <Container style={{ elevation: 5 }}>
          <SectionTitle>
            This is a
            {` ${data.city} `}
            card
          </SectionTitle>
        </Container>
      </TouchableOpacity>
    );
  }

在本例中,卡片将正确显示This is a London card,但在onPress方法中this.props返回undefined

如何访问this.props 对象进行评估?

【问题讨论】:

标签: react-native


【解决方案1】:

您可以通过两种方式解决此问题。支持将这些行添加到构造函数的论点是,新的绑定函数仅在类的每个实例中创建一次。你也可以使用

onPress={this.onCardPressed.bind(this)}

或(ES6):

onPress={() => this.onCardPressed()}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2018-05-09
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多