25

如何添加点击监听器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. 但是,仅使用 button 而不是Flatlist,它可以工作。为什么它在FlatlistrenderItem 中不起作用?

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

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

4 回答 4

24

我用过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);
}
于 2018-07-31T10:31:34.203 回答
19

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

参考TouchableWithoutFeedback这个链接

于 2017-06-17T20:03:36.760 回答
10

我用过TouchableOpacity。它运行良好。这将为您提供点击反馈。不会提供的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>
}
于 2017-10-25T12:14:14.003 回答
1

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

如果您正在寻找一种更广泛且面向未来的方式来处理基于触摸的输入,请查看 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(反应原生):https ://reactnative.dev/docs/pressable
于 2021-12-26T06:33:01.290 回答