【问题标题】:Click listener in flatlist平面列表中的单击侦听器
【发布时间】:2017-11-20 09:16:50
【问题描述】:

如何在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>
}

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

    我使用了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);
    }
    

    【讨论】:

    • 我想更新特定的项目值,那么这个逻辑可以吗?
    • @Anuj 是的,可能。在点击项目时,获取该项目,更新该特定项目的值,然后更新您的数组并重新加载列表。
    • 谢谢我做到了,
    • @Manish 嗨,Manish,我使用的是相同的代码。但是当我在 FlatList 项目上单击两次时,会调用 actionOnRow(item) 。你能告诉我我犯了什么错误吗?
    • @BoominadhaPrakashM 你能分享代码吗?因为它可能是 UI 组件中的问题。
    【解决方案2】:

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

    对于TouchableWithoutFeedback,请参阅此link

    【讨论】:

    • 嗨,我在 flatlist 的 renderItem 中使用了按钮,但点击监听器不起作用。请查看上述问题中的更新。我也使用过 TouchableWithoutFeedback 但没有运气。
    • @AmritaStha 将 onPress={this._listener} 替换为 onPress={this._listener()}
    • 非常感谢它的帮助。实际上绑定函数有效。
    【解决方案3】:

    我使用了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>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多