本项目是基于taro框架的react语言开发,项目中有需要做图片上传的需求,需要支持多图上传,支持图片删除,支持自动添加新增按钮,支持预览功能,支持显示默认图片等功能
要实现以上功能,使用小程序自带的上传组件已经不能够满足项目需求了,于是抱着学习的态度,开始动手撸一个图片上传框架
目录
介绍
本篇要介绍的自定义组件ChooseImageView具有以下功能
- 支持多张图片同时上传
- 支持大图上传图片超过一定范围自动压缩【30M以上的图片能成功上传】
- 支持显示默认图片isDefault=true
- 支持已添加图片的删除功能
- 支持图片预览功能
- 支持详情功能传入mode=“detail”即可实现详情功能
<View className="chooseImageView" >
<View className="choose-img-wrap">
{files.map(data => {
return (
<View className='img-container' key={data.url}>
<Image
className='img'
key={data.url}
onClick={this.onImageClick.bind(this, data)}
src={data.url}
lazyLoad
mode={data.isAdd ? 'aspectFit' : 'aspectFill'}
/>
{
(!(data.isAdd || data.isDefault) && mode === 'add') && <View className='img-delete' onClick={this.onDeleteImage.bind(this, data)}>删除</View>
}
{
data.isDefault && <Image className='flag' mode='widthFix' src={defaultImg}></Image>
}
</View>
)
}
)}
</View>
{/* 设置style内联样式 */}
<Canvas style={{ width: `${canvasWidth}px`, height: `${canvasHeight}px`, position: 'absolute', left: '-1000px', top: '-1000px' }} canvasId='myCanvas' />
</View >
.chooseImageView {
.choose-img-wrap {
display: flex;
flex-wrap: wrap;
.img-container {
height: 203px;
width: calc((100% - 40px) / 3);
margin-top: 20px;
margin-left: 20px;
position: relative;
overflow: hidden;
border-radius: 16px;
&:nth-child(3n + 1) {
margin-left: 0;
}
&:last-child {
margin-bottom: 20px;
}
.img {
width: 100%;
height: 100%;
background-color: #F9F9F9;
}
.flag {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: auto;
}
.img-delete {
background-color: rgba($color: #000000, $alpha: 0.3);
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 50px;
line-height: 50px;
text-align: center;
font-size: 22px;
color: white;
}
}
}
}
以上为全部内容