我最近在桥接本机代码时使用了 Proptypes 和 TS。该项目是在 React 端用 TypeScript 编写的,我在自己的文件中抽象出我在 React 端的原生组件。没有必要担心 PropTypes 如果它不在它自己的文件中,因为我已经通过 TypeScript 验证了数据。
PropTypes 用于在事件回调中处理来自 Swift 的外部数据。我在这里尝试使用 TypeScript 而不是 PropTypes,但是我在引用 React 组件时遇到了问题。
最终,实现 PropTypes 更容易并且似乎没有缺点,因为运行时的数据验证工作得非常好。
请参阅此处的代码以获取更多详细信息:
//CoreView.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {requireNativeComponent, UIManager, findNodeHandle} from 'react-native';
const COMPONENT_NAME = 'CoreView';
const RNCoreView = requireNativeComponent(COMPONENT_NAME);
export default class CoreView extends Component {
  static propTypes = {
    label: PropTypes.array,
    onUpdate: PropTypes.func,
  };
  _onUpdate = event => {
    if (this.props.onUpdate) {
      this.props.onUpdate(event.nativeEvent);
    }
  };
  render() {
    const {label, style} = this.props;
    return (
      <RNCoreView
        style={style}
        label={label}
        onUpdate={this._onUpdate}
        ref={ref => (this.ref = ref)}
      />
    );
  }
  update = (...args) => {
    UIManager.dispatchViewManagerCommand(
      findNodeHandle(this.ref),
      UIManager[COMPONENT_NAME].Commands.obtainLabelData,
      [...args],
    );
  };
}
在 Swift 方面:
//CoreViewManager.m
#import <Foundation/Foundation.h>
#import "React/RCTViewManager.h"
@interface RCT_EXTERN_MODULE(CoreViewManager, RCTViewManager)
//Allow React to send data as props
RCT_EXPORT_VIEW_PROPERTY(onUpdate, RCTDirectEventBlock)
RCT_EXTERN_METHOD(
  obtainLabelData:(nonnull NSNumber *)node
  imageLocation:(nonnull NSString *)imageLocation
)
@end
也...
import Foundation
@available(iOS 11.0, *)
@objc(CoreViewManager)
class CoreViewManager: RCTViewManager {
  override func view() -> UIView! {
    return CoreView()
  }
  
  @objc func obtainLabelData(_ node: NSNumber, imageLocation: NSString!) {
      
      DispatchQueue.main.async {
        let component = self.bridge.uiManager.view(
          forReactTag: node
        ) as! CoreView
        component.update(value: imageLocation)
      }
    }
}