2017-06-17 67 views
2

如何在Flatlist中添加点击监听器?clicklist listeners in 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> 
} 

回答

3

您需要在<TouchableWithoutFeedback>标记内包装行元素(在renderItem方法内)。 TouchableWithoutFeedback需要onPress,因为它是你可以提供onPress事件的道具。

对于TouchableWithoutFeedback请参阅本link

+1

嗨,我已经使用平面列表中的renderItem中的按钮,但点击监听器不工作。请看一下上面问题中的更新。我也使用了TouchableWithoutFeedback,但没有运气。 –

+1

@AmritaStha用onPress = {this._listener()}替换onPress = {this._listener} –

+0

@Aritritstha它工作与否? –

0

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