React Native 原生组件回调JS层方法和 JS 层调用原生组件的事件方法
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在React Native中,原生组件向JS层发送事件的回调可以通过自定义的事件处理系统来实现。以下是一个简单的例子:
首先,在原生代码中定义一个事件:
// 假设这是在Android原生组件中的一部分代码
public class CustomView extends View {
    // ...
 
    public void doSomethingInJS() {
        // 触发事件
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit("customEventName", null);
    }
}然后,在JSX中使用该组件并添加一个监听器:
import { DeviceEventEmitter } from 'react-native';
 
// 在你的组件中
componentDidMount() {
    // 添加监听器
    this.subscription = DeviceEventEmitter.addListener('customEventName', this.handleCustomEvent);
}
 
// 记得取消监听器
componentWillUnmount() {
    this.subscription.remove();
}
 
handleCustomEvent() {
    // 处理事件
    console.log('Event received in JS');
}
 
render() {
    return (
        // ... 你的组件
    );
}在这个例子中,原生组件通过reactContext.getJSModule(...).emit(...)发送事件,而JS层通过DeviceEventEmitter.addListener来监听这个事件。当原生组件触发事件时,JS层中的handleCustomEvent方法会被调用。
评论已关闭