我试图让我的浏览器将一些 DOM 事件发送到 React VR 组件中。
我得到的最接近的是使用“本机模块”的这段代码。
(client.js)
const windowEventsModule = new WindowEventsModule();
function init(bundle, parent, options) {
const vr = new VRInstance(bundle, 'WelcomeToVR', parent, {
...options,
nativeModules: [windowEventsModule]
});
windowEventsModule.init(vr.rootView.context);
vr.start();
return vr;
}
window.ReactVR = {init};
(WindowEventsModule.js)
export default class WindowEventsModule extends Module {
constructor() {
super('WindowEventsModule');
this.listeners = {};
window.onmousewheel = event => {
this._emit('onmousewheel', event);
};
}
init(rnctx) {
this._rnctx = rnctx;
}
_emit(name, ob) {
if (!this._rnctx) {
return;
}
Object.keys(this.listeners).forEach(key => {
this._rnctx.invokeCallback(this.listeners[key], [ob]);
});
}
onMouseWheel(listener) {
const key = String(Math.random());
this.listeners[key] = listener;
return () => {
delete this.listeners[key];
};
}
}
所以我的组件现在可以调用WindowEvents.onMouseWheel(function() {})
,并从 DOM 世界中获取回调。
不幸的是,这只适用于一次。RN 在调用后显然会使我的回调无效。
我还研究this._rnctx.callFunction()
了 ,它可以在称为“可调用模块”的东西上调用任意函数。我不知道如何从那里到达我的组件。
有什么我想念的吗?将来自原生世界的任意消息馈送到 ReactVR 后台工作者的模式是什么?