【问题标题】:update state with selected item in flatlist使用平面列表中的选定项目更新状态
【发布时间】:2021-07-26 09:23:13
【问题描述】:

我有一组图像,我可以使用 flatlist 显示这些图像。我想要一个功能,当您单击图像时,它应该显示在单独的视图中。

下面是我的代码sn-p:

const [selectedImage, setSelectedImage] = useState(joy);
const [imageSet, setImageSet] = useState([joy,anger,concern,depression]);
return (
<SafeAreaView>
    <View style={{width: 100, height: 400}}>
      <Image style={{height: 50, width: 50}} source={selectedImage} />
    </View>
    <FlatList
    horizontal={true}
    showsHorizontalScrollIndicator={false}
    data={imageSet}
    renderItem={({item, index}) => (
        <View>
          <TouchableOpacity
              onPress={(item) => {
              setSelectedImage(item);    // trying to select the image here
              }}>
                <Image
                source={item}
                key={index}
                style={{
                  width: 60,
                  height: 60,
                  resizeMode: 'contain',
                }}
              />
          </TouchableOpacity>
        </View>
    )}
    />
</SafeAreaView>
);

但是点击它时图像没有显示出来。我无法弄清楚问题所在。请帮忙。

【问题讨论】:

    标签: react-native react-hooks react-native-android react-native-ios react-native-flatlist


    【解决方案1】:

    我看到您的代码的问题是您正在将未定义的 TouchableOpacity onPress 中的 item 传递给 setSelectedImage。这就是为什么图像没有设置到您的状态。

    试试这个:

    之前:

    <TouchableOpacity
       onPress={(item) => { <--- Remove this item!!
       setSelectedImage(item)}}>
    

    之后:

     <TouchableOpacity
           onPress={() => { 
           setSelectedImage(item)}}>
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2016-02-13
      相关资源
      最近更新 更多