javascript - 如何使用 React native 获取作为数组项的单击图像的索引
问题描述
我制作了一个数组以从用户那里获取 5 张图像。我需要为用户提供从该数组中动态选择和删除图像的功能。我目前正在使用 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;
};
解决方案
首先不要直接改变状态,这里有更多内容。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;
};
推荐阅读
- docker - Dockerfile 在后台运行脚本而不退出它
- windows - 使用 Ansible 在 Windows 10 VM 中安装和配置 docker 桌面
- c# - AutoMapper 配置验证
- python - 在 Python 中使用 GMAIL API 下载受密码保护的 PDF
- .net - 使用 Aspose 和 IText 使用 .NET 检查 PDF 中的电子签名的问题
- python - 如何在 django API 中创建我的用户时发送重置密码电子邮件?
- django - Django 表单定制
- json - HTTP/JSON 请求?
- c# - 正则表达式匹配 !WSⅡ%^ OR WSⅡ 在 C# 中的字符串
- drupal-modules - Acquia Content Hub 2.x 导入失败