React Native 新版 native call js的方法

前端之家收集整理的这篇文章主要介绍了React Native 新版 native call js的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 集成RCTEventEmitter

@interface CustomEventEmitter :RCTEventEmitter


@end


#import "CustomEventEmitter.h"


@implementation CustomEventEmitter


RCT_EXPORT_MODULE(CustomEventEmitter);


- (instancetype)init

{

self = [superinit];

if (self) {

//因为CustomEventEmitter实例不是自己创建的 故拿不到实例, 想调用该实力的方法需要NSNotificationCenter 这是比较low的地方

[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(updateAddress:)name:@"UpdateAddress"object:nil];

[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(updateTelphone:)name:@"UpdateTelphone"object:nil];

}

returnself;

}


//此方法必须重载

- (NSArray<NSString *> *)supportedEvents

{

return @[@"UpdateAddress"];

}


- (void)updateAddress:(NSNotification *)notification

{

[selfsendEventWithName:@"UpdateAddress"body:@{@"address" :@"SZ"}];

}


- (void)updateTelphone:(NSNotification *)notification

{

[selfsendEventWithName:@"UpdateTelphone"body:@{@"telphone" :@"138"}];

}


2. 在JS需如下操作
  1. import React,{Component} from 'react';
  2. import {
  3.     AppRegistry,StyleSheet,Text,View,    NativeModules,NativeEventEmitter,
  4.     Image,} from 'react-native';
    const CustomEventEmitter = NativeModules.CustomEventEmitter;
  5. const EE = new NativeEventEmitter(CustomEventEmitter);  //创建自定义事件接口  export default class TestOCCallRN extends Component {
  6.     render() {
  7.         return (
  8.             <View style={styles.container}>
  9.                 <Image source={require('./1.png')}
  10.                        style={{width: 400,height: 400}} />
  11.             </View>
  12.         );
  13.     }
  14.     componentWillMount() {
  15.         this.listener = EE.addListener("UpdateAddress",this.updateAddress.bind(this));
  16.     }
  17.     componentWillUnmount() {
  18.         this.listener && this.listener.remove();
  19.         this.listener = null;
  20.     }
  21.     updateAddress(data) {
  22.  console.log(data.address);
  23.     }}
     
    const styles = StyleSheet.create({  
      container: {       
    	 flex: 1,
    	 justifyContent: 'center',255); font-family:Menlo; font-size:9pt">	 alignItems: 'center',255); font-family:Menlo; font-size:9pt"> backgroundColor: '#F5FCFF',255); font-family:Menlo; font-size:9pt">}});
  24. AppRegistry.registerComponent('TestOCCallRN',() => TestOCCallRN);

猜你在找的React相关文章