分享更有价值
被信任是一种快乐

react如何实现图片选择

文章页正文上

这篇文章主要讲解了“react如何实现图片选择”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“react如何实现图片选择”吧! react实现图片选择的方法:1、使用import引入“react-native-image-picker”插件;2、使用“{this.setState({uploadImgs: urls})}}src={uploadImgs}/>”调用实现图片选择上传即可。={6}onchange={urls>React Native七牛上传+本地图片选择参考:

react-native-image-crop-picker图片选择并裁减//这个看需求使用
https://github.com/ivpusic/react-native-image-crop-picker
react-native-image-picker图片选择
https://github.com/react-native-image-picker/react-native-image-picker
react-native-qiniu
https://github.com/buhe/react-native-qiniu

我只要一个多图片上传功能,所以就写简单一点效果已上传状态上传中状态步骤1、手机图片、视频选择功能用react-native-image-picker插件yarn add react-native-image-picker;ios需要pod install;

import{launchCamera,launchImageLibrary,ImageLibraryOptions,PhotoQuality}from'react-native-image-picker';
/**
*从相册选择图片;
*sourceType:'camera'打开相机拍摄图片
**/
exportasyncfunctionchooseImage(options:{
count?:number,
quality?:PhotoQuality
sourceType?:'camera',//默认'album'
}={}){
returnnewPromise(async(resolve,reject)=>{
constOpts:ImageLibraryOptions={
mediaType:'photo',
quality:options.quality||1,
selectionLimit:options.count||1
};
constresult=options.sourceType=='camera'?
awaitlaunchCamera(Opts):
awaitlaunchImageLibrary(Opts);
resolve(result)
})
}
/**
*从相册选择视频;
*sourceType:'camera'打开相机拍摄视频
**/
exportasyncfunctionchooseVideo(options:{
count?:number,
quality?:'low'|'high'
sourceType?:'camera',//默认'album'
}={}){
returnnewPromise(async(resolve,reject)=>{
constOpts:ImageLibraryOptions={
mediaType:'video',
videoQuality:options.quality,
selectionLimit:options.count||1
};
constresult=options.sourceType=='camera'?
awaitlaunchCamera(Opts):
awaitlaunchImageLibrary(Opts);
resolve(result)
})
}

2、七牛上传文件功能

classqiniuUpload{
privateUP_HOST='http://upload.qiniu.com';
//privateRS_HOST='http://rs.qbox.me';
//privateRSF_HOST='http://rsf.qbox.me';
//privateAPI_HOST='http://api.qiniu.com';
publicupload=async(uri:string,key:string,token:string)=>{
returnnewPromise((resolve,reject)=>{
letformData=newFormData();
formData.append('file',{uri:uri,type:'application/octet-stream',name:key});
formData.append('key',key);
formData.append('token',token);

letoptions:any={
body:formData,
method:'post',
};
fetch(this.UP_HOST,options).then((response)=>{
resolve(response)
}).catch(error=>{
console.error(error)
resolve(null)
});
})
}
//...后面再加别的功能
}
constqiniu=newqiniuUpload();
exportdefaultqiniu;
importqiniufrom'@/modules/qiniu/index'
...
/**
*上传视频图片
*/
uploadFile:async(filePath:string)=>{
constres=awaitcreateBaseClient('GET','/v1/file')();//这是接口请求方法,用来拿后端的七牛token、key

if(!res){
returnres;
}
const{key,token}=res;
constfileSegments=filePath.split('.');
constfileKey=key+'.'+fileSegments[fileSegments.length-1];
try{
constresult=awaitqiniu.upload(filePath,fileKey,token)
if(result&&result.ok){
return{
url:ASSET_HOST+'/'+fileKey,//ASSET_HOST是资源服务器域名前缀
};
}else{
returnnull
}
}catch(error){
returnnull;
}
},
...

3、多图上传组件封装(这里Base、Image、ActionSheet都是封装过的,需看情况调整)

importReactfrom'react'
import{
ViewStyle,
StyleProp,
ImageURISource,
ActivityIndicator
}from'react-native'
importBasefrom'@/components/Base';
import{Image,View,Text}from'@/components';//Image封装过的,所以有些属性不一样
importActionSheetfrom"@/components/Feedback/免费云主机、域名ActionSheet";//自己封装
importstylesfrom'./styleCss';//样式就不放上来了
interfaceProps{
type?:'video'
src?:string[]
count?:number
btnPath?:ImageURISource
style?:StyleProp
itemStyle?:StyleProp
itemWidth?:number
itemHeight?:number//默认正方形
onChange?:(e)=>void
}
interfaceState{
imageUploading:boolean
images:string[]
}
/**
*多图上传组件
**type?:'video'
**src?:string[]//图片数据,可用于初始数据
**count?:number//数量
**btnPath?:ImageURISource//占位图
**itemStyle?:item样式,width,height单独设
**itemWidth?:number
**itemHeight?:number//默认正方形
**onChange?:(e:string[])=>void
**/
exportdefaultclassUploaderextendsBase{
publicstate:State={
imageUploading:false,
images:[]
};
publicdidMount(){
this.initSrc(this.props.src)
}
publiccomponentWillReceiveProps(nextProps){
if(nextProps.hasOwnProperty('src')&&!!nextProps.src){
this.initSrc(nextProps.src)
}
}
/**
*初始化以及改动图片
**/
privateinitSrc=(srcProp:any)=>{
if(!this.isEqual(srcProp,this.state.images)){
this.setState({
images:srcProp
})
}
}

publicrender(){
const{style,btnPath,count,itemStyle,itemWidth,itemHeight,type}=this.props;
const{imageUploading,images}=this.state;
letcountNumber=count?count:1
return(


{images.length>0&&images.map((res,ind)=>(


{
this.singleEditInd=ind;
this.handleShowActionSheet()
}}
/>
删除


))}
{images.length
{imageUploading?(



上传中...


):(

{
this.singleEditInd=undefined;
this.handleShowActionSheet()
}}
/>

)}


}


{
if(type=='video'){
this.handleChooseVideo('camera')
}elseif(this.singleEditInd!==undefined){
this.handleChooseSingle('camera')
}else{
this.handleChooseImage('camera')
}
}
},{
name:'相册',
onClick:()=>{
if(type=='video'){
this.handleChooseVideo()
}elseif(this.singleEditInd!==undefined){
this.handleChooseSingle()
}else{
this.handleChooseImage()
}
}
}]}
>

);
}
privategetitemW(){
returnthis.props.itemWidth||92
}
privategetitemH(){
returnthis.props.itemHeight||this.itemW;
}

privateisEqual=(firstValue,secondValue)=>{
/**判断两个值(数组)是否相等**/
if(Array.isArray(firstValue)){
if(!Array.isArray(secondValue)){
returnfalse;
}
if(firstValue.length!=secondValue.length){
returnfalse;
}
returnfirstValue.every((item,index)=>{
returnitem===secondValue[index];
});
}
returnfirstValue===secondValue;
}
privatehandleShowActionSheet=()=>{
this.feedback.showFeedback('uploaderActionSheet');//这是显示ActionSheet选择弹窗。。。
}
privatehandleChooseImage=async(sourceType?:'camera')=>{
const{imageUploading,images}=this.state;
const{count}=this.props
if(imageUploading){
return;
}
letcountNumber=count?count:1
const{assets}=awaitthis.interface.chooseImage({//上面封装的选择图片方法
count:countNumber,
sourceType:sourceType||undefined,
});

if(!assets){
return;
}
this.setState({
imageUploading:true,
});

letrequest:any=[]
assets.map(res=>{
letreq=this.apiClient.uploadFile(res.uri)//上面封装的七牛上传方法
request.push(req)
})
Promise.all(request).then(res=>{
letimgs:any=[]
res.map((e:any)=>{
if(e&&e.url){
imgs.push(e.url)
}
})
imgs=[...images,...imgs];
this.setState({
images:imgs.splice(0,countNumber),
imageUploading:false,
},
this.handleChange
);
})

}
privatesingleEditInd?:number;//修改单个时的索引值
privatehandleChooseSingle=async(sourceType?:'camera')=>{
let{imageUploading,images}=this.state;
if(imageUploading){
return;
}

const{assets}=awaitthis.interface.chooseImage({//上面封装的选择图片方法
count:1,
sourceType:sourceType||undefined,
});
if(!assets){
return;
}
this.setState({
imageUploading:true,
});
constres=awaitthis.apiClient.uploadFile(assets[0].uri)//上面封装的七牛上传方法
if(res&&res.url&&this.singleEditInd){
images[this.singleEditInd]=res.url
}
this.setState({
images:[...images],
imageUploading:false,
},
this.handleChange
);

}
privatehandleChooseVideo=async(sourceType?:'camera')=>{
const{onChange}=this.props
let{imageUploading}=this.state;
if(imageUploading){
return;
}

const{assets}=awaitthis.interface.chooseVideo({
sourceType:sourceType
});
if(!assets){
return;
}
this.setState({
imageUploading:true,
});
constres=awaitthis.apiClient.uploadFile(assets[0].uri)//上面封装的七牛上传方法
if(res&&res.url){
//视频就不在组件中展示了,父组件处理
if(onChange){
onChange(res.url)
}
}
this.setState({
imageUploading:false,
});

}
privatehandleDelete=(ind:number)=>{
let{images}=this.state
images.splice(ind,1)
this.setState({
images:[...images]
},
this.handleChange
)
}
privatehandleChange=()=>{
const{onChange}=this.props
const{images}=this.state
if(onChange){
onChange(images)
}
}
}

4、最后调用

importUploaderfrom"@/components/Uploader";
...
{
this.setState({
uploadImgs:urls
})
}}
src={uploadImgs}
/>
...

感谢各位的阅读,以上就是“react如何实现图片选择”的内容了,经过本文的学习后,相信大家对react如何实现图片选择这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是云技术,小编将为大家推送更多相关知识点的文章,欢迎关注!

相关推荐: CSS如何实现图片渐隐消

这篇文章主要介绍了CSS如何实现图片渐隐消的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇CSS如何实现图片渐隐消文章都会有所收获,下面我们一起来看看吧。 在过往,我们想要实现一个图片的渐隐消失。最常见的莫过于整体透明度的变化,像是…

文章页内容下
赞(0) 打赏
版权声明:本站采用知识共享、学习交流,不允许用于商业用途;文章由发布者自行承担一切责任,与本站无关。
文章页正文下
文章页评论上

云服务器、web空间可免费试用

宝塔面板主机、支持php,mysql等,SSL部署;安全高速企业专供99.999%稳定,另有高防主机、不限制内容等类型,具体可咨询QQ:360163164,Tel同微信:18905205712

主机选购导航云服务器试用

登录

找回密码

注册