如何使用`TouchableOpacity`中的数据获得`onPress`回调

时间:2017-09-04 08:11:54

标签: react-native

我尝试使用ListView来处理TouchableOpacity.onPress中的一行项目,但我尝试的所有内容都以稍微不同的方式失败。

我有renderRow函数,提供给ListView.renderRow。在这里,我想做:

renderRow(rowData) {
  return (
    <TouchableOpacity onPress= { () => this.tapRow(rowData) }>
        <View style={{margin: 5, backgroundColor: "#EEE" }}>
            <Text>{rowData.text}</Text>
        </View>
    </TouchableOpacity>
  )
}

我的tapRow功能是:

tapRow(rowData) {
    console.log( "Tapped Row: " + rowData.id )
}

这会导致错误_this3.tapRow is not a function ... _this3.tapRow is undefined

查看引用我还尝试将this.tapRow = this.tapRow.bind(this)添加到构造函数中,但这并没有帮助。

对于测试,我也完成了onPress={this.tapRow}。这不会导致错误,但从不调用该函数(我在其中执行一个简单的console.log来验证)

如何获取onPress中调用的函数并为其提供参数?

1 个答案:

答案 0 :(得分:0)

在构造函数上绑定constructor (props) { super(props) this.renderRow = this.renderRow.bind(this) } 函数:

{{1}}