如何使用React 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;
};

首先不要直接改变状态,这里有更多关于这方面的内容。splice不会重新运行更新后的数组,而是返回已删除元素的数组。

renderImages = () => {
let imagesToDisplay = [];
const allImages = this.state.image;
allImages.slice(0, 5).map((item, index) => {
imagesToDisplay.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 => {
const image = this.state.image;
image.splice(index, 1);
this.setState({ image });
}}
/>
</View>
);
});
return imagesToDisplay;
};

最新更新