我创建了一个数组来从用户那里获取 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/