【问题标题】:React Native how to call onPress event?React Native 如何调用 onPress 事件?
【发布时间】:2016-06-05 15:33:15
【问题描述】:

您好,我正在使用 React Native 处理我的初学者项目,现在我无法处理 onPress 事件。

渲染

_renderRow(feed) {
  return (
    <TouchableHighlight onPress={() => this._pressRow()}>
      <View style={styles.container}>
        <Image
          source={{uri: feed.thumbnail}}
          style={styles.thumbnail}/>
        <View style={styles.rightContainer}>
          <Text style={styles.title}>{feed.title}</Text>
        </View>
      </View>
    </TouchableHighlight>
  );
}

还有onPress 函数

_pressRow() {
  console.log('list item pressed')  
}

列表视图

<ListView
  dataSource={this.state.dataSource}
  renderRow={this._renderRow}
  style={styles.listView}/>

这是我得到的错误。

undefined 不是函数(评估 _this3._pressRow())

编辑

感谢@Cherniv。我忘记将 this 与 renderRow 函数绑定,这样更改了我的代码并按预期工作:

<ListView
    dataSource={this.state.dataSource}
    renderRow={this._renderRow.bind(this)}
    style={styles.listView}/>

【问题讨论】:

  • 好像你忘了绑定 _renderRow 本身,比如:renderRow={this._renderRow.bind(this, feed)}
  • 嗯,我去看看,这就是我的 renderRow 现在的样子renderRow={this._renderRow}
  • @Cherniv 是的,您对丢失绑定的看法是正确的
  • 酷,不客气
  • TouchableHighlight 中不能使用多个子级。我不认为您使用 TouchableHighlight 是正确的。 ref : facebook.github.io/react-native/docs/touchablehighlight.html 注意:TouchableHighlight 必须有一个孩子(不是零个或多个)

标签: javascript reactjs react-native


【解决方案1】:

是不是因为你在方法声明中忘记了pressRow之前的“_”?

【讨论】:

  • 对不起,这只是复制粘贴
  • 你检查过 feed 的值以及函数 _renderRow 是否被正确调用?
  • @NBeydib 提要看起来不错,列表也是如此,除了 onPress 事件外一切正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多