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

前端之家收集整理的这篇文章主要介绍了react-native 图片选择器react-native-image-picker前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

    @H_502_4@

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

    @H_502_4@

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

    @H_502_4@

    使用:
    声明对像:
    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);

    }

    @H_502_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的实现。

原文链接:https://www.f2er.com/react/307449.html

猜你在找的React相关文章