react-native-image-picker的github官网
react native 之 react-native-image-picke的详细使用图解
-
运行yarn add react-native-image-picker安装到项目运行依赖,此时调试可能会报错,如果报错,需要使用下面的步骤解决:
-
运行react-native link自动注册相关的组件到原生配置中
-
打开项目中的android->app->src->main->AndroidManifest.xml文件,在第8行添加如下配置:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> -
打开项目中的android->app->src->main->java->com->当前项目名称文件夹->MainActivity.java文件,修改配置如下:
package com.native_camera; import com.facebook.react.ReactActivity; // 1. 添加以下两行: import com.imagepicker.permissions.OnImagePickerPermissionsCallback; // <- add this import import com.facebook.react.modules.core.PermissionListener; // <- add this import public class MainActivity extends ReactActivity { // 2. 添加如下一行: private PermissionListener listener; // <- add this attribute /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "native_camera"; } }
-
在项目中添加如下代码:
// 第1步: import {View, Button, Image} from 'react-native' import ImagePicker from 'react-native-image-picker' var photoOptions = { //底部弹出框选项 title: '请选择', cancelButtonTitle: '取消', takePhotoButtonTitle: '拍照', chooseFromLibraryButtonTitle: '选择相册', quality: 0.75, allowsEditing: true, noData: false, storageOptions: { skipBackup: true, path: 'images' } } // 第2步: constructor(props) { super(props); this.state = { imgURL: '' } } // 第3步: <Image source={{ uri: this.state.imgURL }} style={{ width: 200, height: 200 }}></Image> <Button title="拍照" onPress={this.cameraAction}></Button> // 第4步: cameraAction = () => { ImagePicker.showImagePicker(photoOptions, (response) => { console.log('response' + response); if (response.didCancel) { return } this.setState({ imgURL: response.uri }); }) }
-
一定要退出之前调试的App,并重新运行react-native run-android进行打包部署;这次打包期间会下载一些jar的包,需要耐心等待!
网友评论