react native 为图像选择器制作可重用的功能

react native make reuseable function for image picker

我正在尝试使用 react-native imagepicker 库创建一个可恢复的函数,但是当我导入函数时,我从导入它的组件中得到了未定义。使用 console.log 我看到它确实有效。它只是没有显示上传的图片。

我尝试返回源代码和实际功能,但它不起作用

helperfunction.js

import ImagePicker from 'react-native-image-picker';


export const photoUpload =()=>{
    const options = {
        title: 'Select Avatar',
        camera: [{ name: 'fb', title: 'Take a picture' }],
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
      };


     const action = ImagePicker.showImagePicker(options, (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.camera) {
          console.log('User tapped custom button: ', response.camera);
        } else {
          const source = { uri: response.uri };
          console.log(source)
           return  source; 

        }
      })
      return action;



}

App.js

import {photoUpload} from '../../../utilities/helper/photoUpload'

handlePhotoUpload =  async () =>{

    const data = await photoUpload()

    console.log(data) (this comes back undefined)
    if (data){
      this.setState({
        photo: data

      });
    }

  }

如果您查看文档中 showImagePicker 函数的签名,您会发现它没有 return 值:

static showImagePicker(options?, callback)

您仍然从控制台日志中看到结果的原因是,当您调用 showImagePicker 函数时,它会异步调用您的回调函数。要解决此问题,您可以使用这样的承诺:

export const photoUpload = () => {
    const options = {
        title: 'Select Avatar',
        camera: [{name: 'fb', title: 'Take a picture'}],
        storageOptions: {
            skipBackup: true,
            path: 'images',
        },
    };
    return new Promise(((resolve, reject) => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                reject('User cancelled image picker');
            } else if (response.error) {
                reject('ImagePicker Error: ', response.error);
            } else if (response.camera) {
                reject('User tapped custom button: ', response.camera);
            } else {
                const source = {uri: response.uri};
                resolve(source);
            }
        })
    }))
}

您可以保持 app.js 不变,因为您已经在等待 'await' 的承诺解决,这意味着数据变量将导致来自承诺的源结果对象