单击平面列表中的侦听器

Click listener in flatlist

如何在 Flatlist 中添加点击监听器?

我的代码:

renderItem({item, index}){
    return <View style = {{
    flex:1,
    margin: 5, 
    minWidth: 170, 
    maxWidth: 223,
    height: 304,
    maxHeight: 304,
    backgroundColor: '#ccc',
    }}/>
}
render(){
return(<FlatList
contentContainerStyle={styles.list}
data={[{key: 'a'}, {key: 'b'},{key:'c'}]}
renderItem={this.renderItem}
/>);
}
}

更新 1:我使用了按钮,但它在 Flatlist 中不起作用。但是,仅使用按钮而不是 Flatlist,它就可以工作。为什么它在 Flatlist renderItem 中不起作用?

_listener = () => {
    alert("clicked");
}

renderItem({item, index}){
    return<View>
      <Button
          title = "Button"
          color = "#ccc"
          onPress={this._listener}
      />
    </View>
}

您需要将行元素(在您的 renderItem 方法内)包装在 <TouchableWithoutFeedback> 标记内。 TouchableWithoutFeedback 接受 onPress 作为道具,你可以在其中提供 onPress 事件。

TouchableWithoutFeedback 参考这个 link

我用了TouchableOpacity。它正在运行 great.This 会给你点击反馈。 TouchableWithoutFeedback 不会提供。我做了以下事情:

import { View, Text, TouchableOpacity } from "react-native";

。 . .

_onPress = () => {
     // your code on item press
  };

render() {
   <TouchableOpacity onPress={this._onPress}>
      <View>
        <Text>List item text</Text>
      </View>
   </TouchableOpacity>
}

我用了TouchableWithoutFeedback。为此,您需要将所有 renderItem 元素(即您的行)添加到 TouchableWithoutFeedback。然后添加onPress事件并将FaltList项传递给onPress事件。

import {View, FlatList, Text, TouchableWithoutFeedback} from 'react-native';

render() {

  return (

      <FlatList style={styles.list}

          data={this.state.data}

          renderItem={({item}) => (

              <TouchableWithoutFeedback onPress={ () => this.actionOnRow(item)}>

                  <View>
                     <Text>ID: {item.id}</Text>
                     <Text>Title: {item.title}</Text>
                  </View>

             </TouchableWithoutFeedback>

         )}
      /> 
   );
}

actionOnRow(item) {
   console.log('Selected Item :',item);
}

Pressable 组件现在优先于 TouchableWithoutFeedback(和 TouchableOpacity)。根据 TouchableWithoutFeedback 的 React Native 文档:

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the Pressable API.

示例实现:

import { Pressable } from "react-native";

render() {
  return(
    <FlatList
      contentContainerStyle={styles.list}
      data={[{key: 'a'}, {key: 'b'}, {key:'c'}]}
      renderItem={({item}) => (
        <Pressable onPress={this._listener}>
          // BUILD VIEW HERE, e.g. this.renderItem(item)
        </Pressable>
      )}
    />
  );
}

参考资料

  1. TouchableWithoutFeedback(本机响应):https://reactnative.dev/docs/touchablewithoutfeedback
  2. Pressable(React Native):https://reactnative.dev/docs/pressable

如果您遇到平面列表行首次点击问题 请将下面 属性 添加到 flatlist。

disableScrollViewPanResponder = {true}