React Native FlatList onPress for child

2019-04-13 10:40发布

问题:

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)