react调用摄像头拍照

React调用摄像头拍照场景

在一些移动app的个人登陆页面往往有头像的地方,我们可以根据自己的喜好随意的更换我们的头像。那么在react-native的项目中如果轻松的实现这一功能,下面有一些简单的步骤。

React调用摄像头拍照功能实现步骤

  1. 在项目的终端中运行npm install react-native-image-picker@latest --save命令安装到项目运行依赖,此时调试可能会报错,如果报错,需要使用下面的步骤解决:
    • 先删除node_modules文件夹
    • 运行npm i
    • 运行npm start --reset-cache
  2. 在项目的终端中运行react-native link自动注册相关的组件到原生配置中
  3. 打开项目中的android->app->src->main->AndroidManifest.xml文件,在第8行添加如下配置:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  1. 打开项目中的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. 在项目需要使用摄像头拍照的文件中添加如下代码:
// 第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
  });
})
}
  1. 一定要退出之前调试的App,并重新运行react-native run-android进行打包部署;这次打包期间会下载一些jar的包,需要耐心等待!

具体更详细的使用可见如下api
react-native-image-picker的github官网
react native 之 react-native-image-picke的详细使用图解

你可能感兴趣的:(React,react调用摄像头拍照,react设置头像功能,react设置头像功能功能实现)