javascript - 如何使用 React Native 获取单击图像的索引(这是数组的一项)

标签 javascript reactjs native

我创建了一个数组来从用户那里获取 5 张图像。我需要为用户提供动态选择和删除该数组中的图像的功能。我目前正在使用 splice() 方法来执行操作。但是当我选择要删除的图像时..它正在按新闻删除整个图像

renderImages = () => {
  let image = [];
  this.state.image.slice(0, 5).map((item, index) => {
    image.push(
      <View key={index} style={{ padding: 16 }}>
        <Image source={{ uri: item }} style={{ width: 60, height: 60 }} />
        <Icon
          name="window-close"
          size={15}
          color="#d3d3d3"
          style={{ position: "absolute", top: 5, right: 5 }}
          onPress={index => {
            this.setState({ image: this.state.image.splice(index, 1) });
          }}
        />
      </View>
    );
  });
  return image;
};

最佳答案

这里的问题是您使用splice直接在状态上进行突变。您首先需要克隆状态:

renderImages = () => {
  let image = [];
  this.state.image.slice(0, 5).map((item, index) => {
    image.push(
      <View key={index} style={{ padding: 16 }}>
        <Image source={{ uri: item }} style={{ width: 60, height: 60 }} />
        <Icon
          name="window-close"
          size={15}
          color="#d3d3d3"
          style={{ position: "absolute", top: 5, right: 5 }}
          onPress={index => {
            let images = [...this.state.image]
            images.splice(index, 1)

            this.setState({ image: images });
          }}
        />
      </View>
    );
  });
  return image;
};

关于javascript - 如何使用 React Native 获取单击图像的索引(这是数组的一项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61307407/

相关文章:

javascript - WebAssembly 中的 .NET CLR

javascript - 如何停止javascript中的事件捕获?

javascript - 在 React-Admin 中显示一个数组

reactjs - 如何在react中更新reducer状态中的数据

Kotlin/Native - 如何使用 C 库和 Klib 文件?

javascript - 为 flatlist 的所有项目创建一个状态数组。 ( react native )

javascript - 为什么我无法在我的系统中安装 React 和卸载 create-react-app?

javascript - React Native 节标题

android - FileDescriptor在Android中的实际系统文件描述符(作为int)

php - stub PHP native 方法