安装 并 link
yarn add react-native-image-picker
react-native link
配置权限
Ios
android
在/android/app/src/main/AndroidManifest.xml文件中添加
直接上代码
1.引入包
import ImagePicker from 'react-native-image-picker';
2.配置文案和参数,调用。
selectPhotoTapped(){
const options = {
title:'选择图片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相册',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.showImagePicker(options,(response)=>{
if(response.didCancel){
console.warn('cancel')
}else if(response.error){
console.warn(error)
}else{
let source = {uri:response.uri}
this.setState({
headSource:source,
})
}
});
}
以上调用弹出的选择框是默认的,安卓和ios的差距很大,而且安卓上的弹框可丑可丑。。
一般都自定义弹框,点击相机
const options = {
title:'选择图片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相册',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.launchCamera(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = { uri: response.uri };
this.setState({
headSource: source,
headImgDataStr: response.data
},()=>{
this._unloadHeadImage();
});
}
});
点击相册
const options = {
title:'选择图片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相册',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = { uri: response.uri };
console.log(response.data);
this.setState({
headSource: source,
headImgDataStr: response.data
},()=>{
this._unloadHeadImage();
});
}
});
我这里有一个问题,Ios平台上ImagePicker.launchImageLibrary第二次调用打不开相册。如果你知道原因,求告知!!!