React Native | Java和JavaScript互操作
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
// 引入RCTDeviceEventEmitter,用于接收Java发出的事件
import { DeviceEventEmitter } from 'react-native';
export default class RNInteractWithJava extends Component {
constructor(props) {
super(props);
this.state = {
messageFromJava: null
};
}
componentDidMount() {
// 监听来自Java的事件
this.subscription = DeviceEventEmitter.addListener(
'MessageEvent', // 事件名称
(msg) => {
this.setState({ messageFromJava: msg });
}
);
}
componentWillUnmount() {
// 组件卸载时移除监听器
this.subscription.remove();
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
{this.state.messageFromJava ? (
<Text style={styles.instruction}>
Message from Java: {this.state.messageFromJava}
</Text>
) : (
<Text style={styles.instruction}>
Waiting for message from Java...
</Text>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instruction: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('RNInteractWithJava', () => RNInteractWithJava);
这段代码展示了如何在React Native应用中接收来自Java的事件。首先,它引入了DeviceEventEmitter
,然后在组件挂载时使用addListener
监听名为'MessageEvent'的事件,并在组件卸载时移除监听器。这样,每当Java发送事件时,React Native就可以接收到消息,并更新组件的状态。
评论已关闭