【问题标题】:Call this.props in function outside render gives undefine在渲染外部的函数中调用 this.props 会给出 undefine
【发布时间】:2017-12-12 12:42:03
【问题描述】:

我的平面列表有这个问题。基本上我正在破坏我的代码以使其更具可读性。但是,每当我在渲染之外调用 this.props 时,我的问题都会给我 undefine 。下面是我的代码:

renderItem(item) {
  console.log(this.props) // Gives me undefine
  return (
    <ListItem button>
      <Text>{item.item.name }</Text>
    </ListItem>
  )
}
render() {
  return (
    <FlatList
      keyboardShouldPersistTaps={'always'}
      data={countries.payload.data}
      renderItem={this.renderItem}
      keyExtractor={item => item.name}
    />
  )
}

但是如果我没有将renderItem分离到其他函数。我可以访问 this.props:

render() {
  return (
    <FlatList
      keyboardShouldPersistTaps={'always'}
      data={countries.payload.data}
      renderItem={({item, index}) => (
        <ListItem button onPress={() => this.props.onPressAction()}> // I get the correct value
          <Text>{item.name }</Text>
        </ListItem>
      )}
      keyExtractor={item => item.name}
    />
  )
}

【问题讨论】:

  • renderItem={this.renderItem.bind(this}
  • 这里有一点错别字(缺少右括号),应该是renderItem={this.renderItem.bind(this)}

标签: react-native jsx


【解决方案1】:

当使用 react-native 和 ES6 classes 时,它不会自动绑定在你的类上声明的函数,所以 this 将是一个活动对象,代表未知上下文甚至 undefined 这导致 @987654324 @成为undefined

我们需要自己处理 this 的正确值到我们的方法中。因此,要么使用:

  • 更改为this.renderItem.bind(this)
  • 或使用箭头函数,如renderItem= () =&gt; {}

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多