- 要导出的原生组件是一个走势图的组件。
#import <UIKit/UIKit.h>
@interface JFLineChartView : UIView
@property (nonatomic, copy) NSString * fundId; //基金 id
@property (nonatomic, copy) NSString * host; //请求的 host 地址
//根据传入的时间段加载净值数据
- (void)loadNetValueWithDate:(NSString *)str;
@end
- 新建一个类,导出该组件
#import <React/RCTViewManager.h>
#import "JFLineChartView.h"
NS_ASSUME_NONNULL_BEGIN
//继承RCTViewManager
@interface RNTFundTrendManager : RCTViewManager
@end
NS_ASSUME_NONNULL_END
#import "RNTFundTrendManager.h"
#import "JFLineChartView.h"
#import <React/RCTViewManager.h>
#import <React/RCTUIManager.h>
@implementation RNTFundTrendManager
RCT_EXPORT_MODULE(RNTFundTrend)
RCT_EXPORT_VIEW_PROPERTY(fundId, NSString)
RCT_EXPORT_VIEW_PROPERTY(host, NSString)
/* 暴露给 js 调用的方法
rctTag:js 中获取的组件的 tag
time:js 中传递的参数
js调用示例:NativeModules.RNTFundTrend.loadWithTime(findNodeHandle(this), '月');
RNTFundTrend:导出的 module 名称 //RCT_EXPORT_MODULE(RNTFundTrend)
loadWithTime:原生组件暴露给 js 的方法名,第一个参数必须为 rctTag
'月':作为参数值传递给第二个参数 time
*/
RCT_EXPORT_METHOD(loadWithTime:(nonnull NSNumber *)rctTag time:(NSString *)time) {
dispatch_async(self.bridge.uiManager.methodQueue, ^{
[self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {
UIView * view = viewRegistry[rctTag];
if ([view class] == JFLineChartView.class) {
JFLineChartView * v = (JFLineChartView *)view;
[v loadNetValueWithDate:time];
}
}];
});
}
- (UIView *)view {
JFLineChartView * v = [[JFLineChartView alloc] init];
return v;
}
@end
- js 中新建一个 js 文件,对导出的组件进行封装
import {
requireNativeComponent, UIManager, findNodeHandle, NativeModules,
} from 'react-native';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line react/prefer-stateless-function
class JRNFundTrendView extends Component {
componentDidMount() {
//RNTFundTrend:原生中导出的组件的名字
//loadWithTime: 要调用的原生组件的方法
//findNodeHandle(this):js 中该封装的组件的 id
//‘月’:传递给原生方法中的参数
NativeModules.RNTFundTrend.loadWithTime(findNodeHandle(this), '月');
}
// loadData = (time) => {
// this.sendCommand('loadWithTime', time);
// const { RNTFundTrendManager } = NativeModules;
// RNTFundTrendManager[command].loadWithTime(findNodeHandle(this.trend), time);
// UIManager.dispatchViewManagerCommand(
// findNodeHandle(this.trend),
// UIManager.RNTFundTrendView.Commands.loadWithTime,
// [time],
// );
// };
render() {
return (
<RNTFundTrendView {...this.props} />
);
}
}
JRNFundTrendView.propTypes = {
// eslint-disable-next-line react/require-default-props
fundId: PropTypes.string,
// eslint-disable-next-line react/require-default-props
host: PropTypes.string,
};
//第一个参数是原生中导出的模块的名称
//RCT_EXPORT_MODULE(RNTFundTrend)
//第二个参数是封装的组件的名称,这里就是 js 文件的类名
const RNTFundTrendView = requireNativeComponent('RNTFundTrend', JRNFundTrendView);
export default JRNFundTrendView;
- 调用逻辑
在组件的componentDidMount()方法中,开始调用原生组件的loadWithTime()方法,该方法接受 2 个参数,第一个参数是该组件的 id,第二个参数是字符串类型,React-Native 通过该 id 找到对应的原生组件,然后将第二个参数传递过去,原生组件可以拿到该参数后,去调用对应的方法。
网友评论