React Native 新版 native call js的方法
来源:互联网 发布:手机购物比价软件 编辑:程序博客网 时间:2024/05/19 08:04
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);
- React Native 新版 native call js的方法
- 【React Native】React Native的bind方法
- react native js中调用native中的方法
- React Native:JS调用Android本地方法
- React Js 与React Native
- React Js 与React Native
- React Native调试方法
- React Js 与 Native 之间的通信
- android 添加React Native支持更新版
- 【React Native】常见的函数绑定方法
- React-Native的基本属性方法
- React Native 链接原生库的方法
- react-native调用Android的原生方法
- React native 开发常用的方法
- React Native Don't Call PropTypes Warning
- React-Native:调用(Android)Native方法
- React Native开发写的JS和React入门知识
- React-Native的学习指南
- 1005. 后缀表达式计算
- 【第六周 项目2- 建立链栈算法库】
- Python排序
- 第八周--项目五--计数的模式匹配--
- 第八周项目三(1)顺序串算法
- React Native 新版 native call js的方法
- 第八周项目4—逆序排列
- 【第八周—项目2 - 建立链串的算法库】
- 最新版支付宝集成
- 数据结构——括号匹配
- deeplearning 入门文章和书本
- Python--OS模块
- 使用HiVE分析数据
- 正则表达式(精华)