React Native 混编2 - 原生与RN之间相互调用

如果对你的思路有丁点的帮助,麻烦帮忙点个哟,谢谢!!!!

  • 文章的目的:
    • 1、在原生工程中的MyViewController下加载一个RN 组件
    • 2、点击RN组件调用原生的方法让MyViewController出现一个按钮(名字由RN传递过来)
    • 3、点击新按钮调用RN的方法
React Native 混编2 - 原生与RN之间相互调用_第1张图片
未命名.gif
  • 具体实现
我们新建一个原生工程 MyNativeDemo

0、在原生工程下创建一个VC 作为窗口的跟控制器
我创建一个继承自UIViewController的控制器MyViewController并把它包装一个导航控制器

MyViewController.m的代码如下

#import "MyViewController.h"

#import "ComponentView.h"

#import 

@interface MyViewController ()
@property (nonatomic, strong) RCTResponseSenderBlock myBlock;   // 导入 #import 
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  self.title = @"原生导航控制器";
  self.view.backgroundColor = [UIColor redColor];
  
  
  ComponentView *myView = [[ComponentView alloc] init];
  myView.frame = CGRectMake(50, 150, 200, 300);
  [self.view addSubview:myView];
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUpRightButton:) name:@"newButton" object:nil];
  
}

- (void)setUpRightButton:(NSNotification *)info
{
  
  NSLog(@"%@ %@",info.userInfo[@"name"],info.userInfo[@"block"]);
  
  NSString *buttonName = info.userInfo[@"name"];
  
  _myBlock = info.userInfo[@"block"];
  
  UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
  [btn setTitle:buttonName forState:UIControlStateNormal];
  [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  [btn sizeToFit];
  [btn addTarget:self action:@selector(clickNewButton:) forControlEvents:UIControlEventTouchUpInside];
  
  UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
  self.navigationItem.rightBarButtonItem = item;
}

// 点击按钮执行的方法 -调用RN
- (void)clickNewButton:(UIButton *)btn
{
  btn.selected = !btn.selected;
  
  NSArray *events = @[@(btn.selected)];
  
  if (_myBlock) {
    _myBlock(@[[NSNull null],events]);
  }
}
@end

1、在RN 中新建一个js文件 RNComponent.js

import React, { Component } from 'react';import {
    AppRegistry,
    StyleSheet,
    Text,
    View, 
   TouchableOpacity, 
   NativeModules} from 'react-native';
var RNManager = NativeModules.RNManagervar 
export default class RNComponent extends Component {    constructor(props){
        super(props);
        this.state = {
            show:false,
            otherShow:false
        }    }
    render(){ 
       console.log(this.props);
        return( 
           
                
{this.clickNewButton()}}>
                                            第一个RN的按钮
                     
               
                {this.showView()}
                {this.otherShowView()}
             
       )    }
    showView(){
        return(
            this.state.show ? (
                {this.otherShowClick()}}> 
                                           第二个RN的按钮 
                    
               
            ) : null
        )    }
    otherShowView(){ 
       return(
            this.state.otherShow ? ( 
               
                    第三个RN的按钮
                 
           ) : null 
       )    } 
   otherShowClick(){
        this.setState({
            otherShow:!this.state.otherShow 
       })    } 
   clickNewButton(){
        RNManager.clickRNNoti('新按钮',(error,events)=>{            if(error){ 
               console.error(error); 
           }else{
                this.setState({ 
                   show:events[0] 
               })
            }
        })
    }}
const styles = StyleSheet.create({
    container:{
        width:100, 
       height:300,
        backgroundColor:'green',
        alignItems:'center', 
       justifyContent:'center'
    }, 
   secondViewStyle:{ 
       marginTop:30, 
       backgroundColor:'yellow'
    }})
AppRegistry.registerComponent('RNComponent', () => RNComponent);

2、 在原生工程中创建一个继承自UIView的类ComponentView 封装我们的RNComponent组件

在ComponentView.m文件下添加如下代码

#import "ComponentView.h"

#import   // 导入头文件 *****

@implementation ComponentView

- (void)layoutSubviews
{
  [super layoutSubviews];
  
  NSURL *url = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:url moduleName:@"RNComponent" initialProperties:nil launchOptions:nil];
  
  rootView.frame = self.bounds;
  [self addSubview:rootView];
}

3、创建一个继承自NSObject的管理类RNManager,作用是:点击RN按钮的时候,通知原生做某事

注意:因为该管理类是RN和OC交互的接口,所以需要导入几个头文件

RNManager.h的代码

#import 
#import 

@interface RNManager : NSObject 

@end

RNManager.m的代码

#import "RNManager.h"

@interface RNManager ()

@property (nonatomic, strong) RCTResponseSenderBlock myBlock;

@end
@implementation RNManager

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(clickRNNoti:(NSString *)buttonName callBack:(RCTResponseSenderBlock)callBack)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    
    NSDictionary *dic = @{@"name":buttonName,@"block":callBack};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"newButton" object:nil userInfo:dic];
  });
}
@end

你可能感兴趣的:(React Native 混编2 - 原生与RN之间相互调用)