React Native 新版 native call js的方法

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

1. 集成RCTEventEmitter

@H_404_3@@interface CustomEventEmitter :RCTEventEmitter


@end


@H_404_3@#import "CustomEventEmitter.h"


@H_404_3@@implementation CustomEventEmitter


@H_404_3@RCT_EXPORT_MODULE(CustomEventEmitter);


- (instancetype)init

{

@H_404_3@self = [@H_404_3@superinit];

@H_404_3@if (@H_404_3@self) {

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

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

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

}

returnself;

}


//此方法必须重载

- (NSArray<NSString *> *)supportedEvents

{

@H_404_3@return @[@"UpdateAddress"];

}


- (@H_404_3@void)updateAddress:(NSNotification *)notification

{

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

}


- (@H_404_3@void)updateTelphone:(NSNotification *)notification

{

[@H_404_3@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',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">}});

AppRegistry.registerComponent('TestOCCallRN',() => TestOCCallRN);
原文链接:https://www.f2er.com/react/305706.html

猜你在找的React相关文章