[英]How to get index of the clicked images which is an item of array using React native
我制作了一个数组以从用户那里获取 5 张图像。 我需要为用户提供 select 的功能,并从该数组中动态删除图像。 我目前正在使用 splice() 方法进行操作。 但是当我选择要删除的图像时..它正在删除整个图像 onPress
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;
};
首先不要直接对 state 进行变异,这里有更多信息。 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;
};
这里的问题是您使用splice
直接在 state 上进行突变。 您首先需要克隆 state:
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.