React Native FlatList onPress for child

狂风中的少年 提交于 2019-12-06 09:22:15

问题


I'm trying to wire up a press handler for an image that's nested within a React Native FlatList. I've verified that the function is being passed in via props, by calling the function directly inside my component and that worked fine. Below is a reduced test case. I've also tried setting the onPress on the Image, with identical results.

const PostList = ({posts, onActLike, currentUser}) => {
  return (
    <FlatList
      data={ posts }
      keyExtractor={ (item) => item.id }
      renderItem={ ({item}) => {
        return (
          <View>
            <Image
              source={ {uri: item.media.url} }
              resizeMode="cover"
            />
            <View>
              <View
                onPress={ (item) => {
                  onActLike(item);
                } }
              >
                {
                  currentUser.likedMedia.indexOf(item.id) > -1 &&
                    <Image
                      source={ require('../assets/images/like_filled.png') }
                      style={ {width: 20, height: 17} }
                      resizeMode='contain'
                    />
                }
                {
                  currentUser.likedMedia.indexOf(item.id) === -1 &&
                    <Image
                      source={ require('../assets/images/like_unfilled.png') }
                      style={ {width: 20, height: 17} }
                      resizeMode='contain'
                    />
                }
              </View>
            </View>
          </View>
        )
      } }
    />
  )
}

回答1:


View doesn't accept an onPress function nor does Image. You need to wrap the View in a Touchable (TouchableOpacity, TouchableHighlight, etc)



来源:https://stackoverflow.com/questions/45177077/react-native-flatlist-onpress-for-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!