React-Native中通过JS调用原生模块

734 查看

官方教程中有讲述在RN中如何集成原生模块(iOS日历组件)
这里我也写了一个简单的示例,目标是 实现消息提示框(Toast)

源码还在这里

一、iOS

在React Native中,一个“原生模块”就是一个实现了“RCTBridgeModule”协议的Objective-C类,其中RCT是ReaCT的缩写。

1、原生部分:
  • NativeToast.h

      #import "RCTBridgeModule.h"
      #import "RCTLog.h"
      #import <UIKit/UIKit.h>
    
      @interface NativeToast : NSObject <RCTBridgeModule>
    
      @end
  • NativeToast.m

    必须明确的声明要给Javascript导出的方法,否则React Native不会导出任何方法。声明通过RCT_EXPORT_METHOD()宏来实现:

    #import "NativeToast.h"
    #import "Global.h"
    @implementation NativeToast 
    RCT_EXPORT_MODULE();
    #pragma mark iOS Native Toast
    RCT_EXPORT_METHOD(showMessage:(NSString *)message showTime:(NSInteger)showTime positions:(NSString *)position){
      NSLog(@"__canshu position = %@ showTime = %ld",position,showTime);
      UIWindow *window = [UIApplication sharedApplication].keyWindow;
      UIView *showView = [[UIView alloc] init];
      [showView setUserInteractionEnabled:NO];
      dispatch_async(dispatch_get_main_queue(), ^{
        [showView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8f]];
        showView.layer.cornerRadius = 5.0f;
        showView.layer.masksToBounds = YES;
        [window addSubview:showView];

        UILabel *label = [[UILabel alloc] init];
        label.text = message;
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = 1;

        label.numberOfLines = 0;
        label.font = [UIFont boldSystemFontOfSize:TOAST_FONT_SIZE];
        CGRect realRect = [message boundingRectWithSize:CGSizeMake(TOAST_MAX_WIDTH, TOAST_MAX_HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font}  context:nil];
        CGSize labelSize = realRect.size;
        labelSize.height = labelSize.height < TOAST_MIN_HEIGHT ? TOAST_MIN_HEIGHT : labelSize.height;
        labelSize.width = labelSize.width < TOAST_MIN_WIDTH ? TOAST_MIN_WIDTH : labelSize.width;
        label.frame = CGRectMake(10, 5, labelSize.width, labelSize.height);
        [showView addSubview:label];

        CGRect rect = [[UIScreen mainScreen] bounds];
        CGSize size = rect.size;
        CGFloat width = size.width;
        CGFloat height = size.height;
        CGFloat positionPoint = 0.5;
        if (position) {
          if ([position isEqualToString:@"top"]) {
            positionPoint = 0.2;
          }else if ([position isEqualToString:@"center"]){
            positionPoint = 0.5;
          }else if ([position isEqualToString:@"bottom"]){
            positionPoint = 0.8;
          }
        }
        NSInteger realShowTime = showTime;
        if (realShowTime < 1) {
          realShowTime = 1;
        }else if (realShowTime > 5){
          realShowTime = 5;
        }
        showView.frame = CGRectMake((width - labelSize.width - 20) / 2, height * positionPoint, labelSize.width + 20, labelSize.height + 10);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(realShowTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [UIView animateWithDuration:1 animations:^{
            showView.alpha = 0;
          } completion:^(BOOL finished){
            [showView removeFromSuperview];
          }];
        });
      });
    }
    @end
  • 通过上边的代码我们就导出了一个“showMessage”的方法,接受三个参数,这个方法可以在JS内部调用
2、JS中调用

ListViewLoadMore/app/components/ProductImageShow.js

import {
    //...
    NativeModules,
} from 'react-native'
class ProductImageShow extends Component {
    //...
    _toast() {
        // showMessage('提示信息内容','显示时长1~5秒','位置['top','center','bottom']')
        NativeModules.NativeToast.showMessage(
            `提示信息\n可以控制显示的时间\nshowTime:[1~5]\n可以控制提示信息显示的位置\nposition:['top','center','bottom']`,
            5,
            'center'
        )
    }

    render() {
        return (
            <View style={ styles.mainView }>
                //...
                <TouchableOpacity onPress={ this._toast.bind(this) }>
                    <View style={ styles.bottomTitleView }>
                        <Text style={ styles.bottomTitle }>点击图片可以去图文详情页</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}
3、效果图

toast

二、Android

....

待补充。。。。