一、點(diǎn)擊頁面按鈕硫嘶,原生向JavaScript端發(fā)送事件
第一步:創(chuàng)建MyModule
public class MyModule extends ReactContextBaseJavaModule {
public MyModule(ReactApplicationContext reactContext) {
super(reactContext);
//給上下文對象賦值
Test.myContext=reactContext;
}
@Override
public String getName() {
return "MyModule";
}
@ReactMethod
public void NativeMethod()
{
//調(diào)用Test類中的原生方法。
new Test().fun();
}
}
第二步:創(chuàng)建MyPackage
public class MyPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules=new ArrayList<>();
modules.add(new MyModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
第三步:創(chuàng)建Test
public class Test {
//定義上下文對象
public static ReactContext myContext;
//定義發(fā)送事件的函數(shù)
public void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params)
{
System.out.println("reactContext="+reactContext);
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName,params);
}
public void fun()
{
//在該方法中開啟線程情连,并且延遲3秒蛔外,然后向JavaScript端發(fā)送事件冀值。
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//發(fā)送事件,事件名為EventName
WritableMap et= Arguments.createMap();
sendEvent(myContext,"EventName",et);
}
}).start();
}
}
第四步:index.android.js中處理
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
DeviceEventEmitter,
NativeModules,
View
} from 'react-native';
export default class ReactAndroid extends Component {
componentWillMount(){
//監(jiān)聽事件名為EventName的事件
// DeviceEventEmitter.addListener('EventName', function() {
// this.showState();
// alert("send success");
// // this.showState();
// });
DeviceEventEmitter.addListener('EventName', ()=> {
this.showState();
alert("send success");
});
}
constructor(props) {
super(props);
this.state = {
content: '這個是預(yù)定的接受信息',
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}
onPress={this.callNative.bind(this)}
>
當(dāng)你點(diǎn)我的時候會調(diào)用原生方法姆怪,原生方法延遲3s后會向前端發(fā)送事件叛赚。
前端一直在監(jiān)聽該事件,如果收到稽揭,則給出alert提示!
</Text>
<Text style={styles.welcome} >
{this.state.content}
</Text>
</View>
);
}
callNative()
{
NativeModules.MyModule.NativeMethod();
}
showState()
{
this.setState({content:'已經(jīng)收到了原生模塊發(fā)送來的事件'})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('ReactAndroid', () => ReactAndroid);