React-Native如何从平面列表中的项目处理onPress ???

时间:2018-09-05 10:25:29

标签: reactjs react-native react-native-ios react-native-flatlist

我的FlatList是无状态组件,当按下项目时,我想通过调用方法“ handleOnPress”来处理onPress。我该怎么做 ?? 以下是示例代码。
`

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
  <TouchableWithoutFeedback onPress={ () => props.onPress}>
      ....
  </TouchableWithoutFeedback>
  )
}

`

2 个答案:

答案 0 :(得分:2)

您的代码存在问题,这是onPress={props.onPress},您的renderItem函数不知道(props)它所知道的只是传递给它的item参数。

如果您这样做

onPress={() => alert("clicked")}

它将起作用。通过数据传递onPress函数或将renderItem函数绑定到构造函数中,然后调用

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

答案 1 :(得分:1)

您可以尝试一下吗?

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
    <TouchableWithoutFeedback onPress={props.onPress}>
      <View>
        ....
      </View>
    </TouchableWithoutFeedback>
  )
}

请注意这两个链接。

https://facebook.github.io/react-native/docs/flatlist

TouchableWithoutFeedback with custom component inside doesn't fires onPress callback

区别在于,将回调作为参数并添加了View层。