react-native 图片选择器react-native-image-picker

react-native android端的UI接口属性赶脚都要比ios少很多,图片选择貌似还没有对应官方api。这里使用一个第三的开源库:react-native-image-picker。搬砖记录下:

  1. 首先下载这个包包:
    进入工程根目录敲入:
    npm install react-native-image-picker@latest –save
    这里可能会有网络延迟等原因,不能完全下载,可以直接下载zip压缩包,解压之后放到yourProject/node_modules/下面就ok了。

  2. 然后在工程中加入以来选项:
    在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’)
    }

  3. 使用:
    声明对像:
    private ImagePickerPackage mImagePicker;

    在MainActivty中添加该module:
    mReactInstanceManager = ReactInstanceManager.builder()

    // register package here
    添加onActivityResult数据:
    @Override
    public void onActivityResult(final int requestCode,final int resultCode,final Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    // handle onActivityResult
    mImagePicker.handleActivityResult(requestCode,data);

    }

  4. 接下来就可以在js中使用该module了
    var UIImagePickerManager = require(‘NativeModules’).UIImagePickerManager;
    一些设置参数:
    var options = {
    title: ‘Select Avatar’,// specify null or empty string to remove the title
    cancelButtonTitle: ‘Cancel’,
    takePhotoButtonTitle: ‘Take Photo…’,// specify null or empty string to remove this button
    chooseFromLibraryButtonTitle: ‘Choose from Library…’,// specify null or empty string to remove this button
    customButtons: {
    ‘Choose Photo from Facebook’: ‘fb’,// [Button Text] : [String returned upon selection]
    },
    maxWidth: 100,
    maxHeight: 100,
    quality: 0.2,
    allowsEditing: false,// Built in iOS functionality to resize/reposition the image
    noData: false,// disables the base64 data field from being generated (greatly improves performance on large photos)
    storageOptions: { // if this key is provided,the image will get saved in the documents directory (rather than a temporary directory)
    skipBackup: true,// image will NOT be backed up to icloud
    path: ‘images’ // will save image at /Documents/images rather than the root
    }
    };
    选择开启摄像头:
    // Launch Camera:
    UIImagePickerManager.launchCamera(options,(didCancel,response) => {
    // Same code as in above section!
    });
    直接在文件中选取图片
    // Open Image Library:
    UIImagePickerManager.launchImageLibrary(options,response) => {
    // Same code as in above section!
    });

其实这个第三方包是一个好的学习react-native的demo,可以根据其构建思路写自己的native modules,这样在js中就能够调用本地组件、接口,可以极大地丰富hybird app。

下一篇,继续自定义module的实现。

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...