【问题标题】:React-Native How to handle onPress from Item in flatlist ???React-Native 如何处理来自平面列表中的项目的 onPress ???
【发布时间】:2019-02-10 11:09:49
【问题描述】:

我的 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>
  )
}

`

【问题讨论】:

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


【解决方案1】:

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

如果你这样做

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

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

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

【讨论】:

  • 我该如何解决? @ArkaneKhan
【解决方案2】:

你可以试试这个吗?

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

不同之处在于,将回调作为参数并添加视图层。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2022-07-12
    • 2021-11-12
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多