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

2016-12-09  本文已影响126人  奔波灞儿

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

未命名.gif
我们新建一个原生工程 MyNativeDemo

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

MyViewController.m的代码如下

#import "MyViewController.h"

#import "ComponentView.h"

#import <RCTBridge.h>

@interface MyViewController ()
@property (nonatomic, strong) RCTResponseSenderBlock myBlock;   // 导入 #import <RCTBridge.h>
@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( 
           <View style={styles.container}>
                <TouchableOpacity onPress={()=>
{this.clickNewButton()}}>
                    <View style={styles.secondViewStyle}>                        <Text>第一个RN的按钮</Text>
                    </View> 
               </TouchableOpacity>
                {this.showView()}
                {this.otherShowView()}
            </View> 
       )    }
    showView(){
        return(
            this.state.show ? (
                <TouchableOpacity onPress={()=>{this.otherShowClick()}}> 
                   <View style={styles.secondViewStyle}>                        <Text>第二个RN的按钮</Text> 
                   </View> 
               </TouchableOpacity>
            ) : null
        )    }
    otherShowView(){ 
       return(
            this.state.otherShow ? ( 
               <View style={styles.secondViewStyle}>
                    <Text>第三个RN的按钮</Text>
                </View> 
           ) : 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 <RCTRootView.h>  // 导入头文件 *****

@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 <Foundation/Foundation.h>
#import <RCTBridgeModule.h>

@interface RNManager : NSObject <RCTBridgeModule>

@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
上一篇 下一篇

猜你喜欢

热点阅读