当前位置: 首页 > 工具软件 > NativeCall > 使用案例 >

React Native 新版 native call js的方法

阳光辉
2023-12-01

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需如下操作

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    NativeModules,
    NativeEventEmitter,
    Image,
} from 'react-native';
const CustomEventEmitter = NativeModules.CustomEventEmitter;
const EE = new NativeEventEmitter(CustomEventEmitter);  //创建自定义事件接口

export default class TestOCCallRN extends Component {
    render() {
        return (
            <View style={styles.container}>

                <Image source={require('./1.png')}
                       style={{width: 400, height: 400}} />
            </View>
        );
    }

    componentWillMount() {
        this.listener = EE.addListener("UpdateAddress", this.updateAddress.bind(this));
    }

    componentWillUnmount() {
        this.listener && this.listener.remove();
        this.listener = null;
    }

    updateAddress(data) {
	console.log(data.address);
}}

const styles = StyleSheet.create({
container: {
	 flex: 1,
	 justifyContent: 'center',
	 alignItems: 'center',
	backgroundColor: '#F5FCFF',
}});
AppRegistry.registerComponent('TestOCCallRN', () => TestOCCallRN);
 
 

 类似资料: