我最近在桥接本机代码时使用了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],
);
};
}
在本土方面:
//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)
}
}
}