原生组件及原生方法调用详解

更新时间:2021-08-27 11:07:18下载pdf

1. 使用 Native 封装方法 api(以 TYRCTCameraManager 为例)

1.1 Rn 引入 Native 封装模块(cameramanager.js)

import { NativeModules } from 'react-native';

export default NativeModules.TYRCTCameraManager;

1.2 使用此封装模块的方法

import CameraManager from './cameramanager.js';

// 调用Native封装方法模块TYRCTCameraManager中的connect方法
CameraManager.connect(
      res => {
       console.log(res, 'P2P连接成功');
      },
      err => {
       console.log(res, 'P2P建立失败');
      }
    );

2. 使用 Native 封装组件(以 TYRCTCameraPlayer 为例)

2.1 RN 引入 Native 封装组件(cameraPlayer.js), 播放器

import React from 'react';
import { requireNativeComponent, View } from 'react-native';
import PropTypes from 'prop-types';

// 引入原生组件
const Player = requireNativeComponent('TYRCTCameraPlayer', CameraPlayer, {
  nativeOnly: { onChange: true }
});
// 原生组件引入再封装
class CameraPlayer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <Player
        {...this.props}
        onChange={event => {
          this.props.onChangePreview(event);
        }}
      />
    );
  }
}

CameraPlayer.propTypes = {
  action: PropTypes.number.isRequired,
  onChangePreview: PropTypes.func.isRequired,
  ...View.propTypes,
};

module.exports = CameraPlayer;