组件的github地址 https://github.com/react-community/react-native-image-picker
安装
yarn add react-native-image-picker
保险起见 执行下 react-native link
适配IOS
1.添加权限
在info.plist中配置
NSPhotoLibraryUsageDescription
和
NSCameraUsageDescription
(会自动添加Privacy - Camera Usage Description和Privacy - Photo Library Usage Description,避免查找麻烦)
2.下图两处是否自动添加上了,如果没有link 或者手动添加
react-native link react-native-image-picker
适配android
1.添加权限
在/android/app/src/main/AndroidManifest.xml文件中添加
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.link后下面的默认已经添加了,最好检查一下
android/settings.gradle文件中
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(settingsDir, '../node_modules/react-native-image-picker/android')
android/app/build.gradle文件的dependencies中
compile project(':react-native-image-picker')
/android/app/src/main/java/com/newredsj/MainApplication.java文件中
import com.imagepicker.ImagePickerPackage; //导包
new ImagePickerPackage() //getPackages方法中
JS代码
先定义
const photoOptions = {
title:'请选择',
quality: 0.8,
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'选择相册',
allowsEditing: true,
noData: false,
storageOptions: {
skipBackup: true,
path: 'images'
}
};
再使用
choosePicker=()=>{
ImagePicker.showImagePicker(photoOptions, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
}
OK,完结! 有问题可以加QQ群讨论:131657381
之前我也文章也是可以任意转载的,但是有些人原封不动copy过去,也不说明是转载的,所以以后我的文章未经本人同意禁止转载,谢谢!