从页面JS中访问React对象? [英] Access React Object from within page JS?

查看:96
本文介绍了从页面JS中访问React对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ReactVr对象,我使用下面的代码进行渲染。在React初始化后,我定期接收服务器更新,我想将其作为道具传递给React,我该怎么做?可以从我的普通JS中设置React对象中的道具吗?

I have a ReactVr object which I am rendering with the code below. After React is initialised I am periodically receiving server updates which I want to pass into React as props, how can I do this? Can props in the React object be set from my "normal" JS?

ReactVR.init(
    './build/index.bundle.js',
    document.body,
    // third argument is a map of initialization options
    {
      initialProps: {
        source: 'world.json',
         userType: "typ1"
        },
      cursorVisibility: 'visible'
    }
  );

编辑:服务器更新是通过Websockets连接来的,但是从React内部没有收到消息,仅在普通JS中。

Server updates are coming via a Websockets connection, but from within React the messages are not being received, only in the "normal" JS.

在普通JS中,这将从服务器返回数据,如果我在React中使用相同的连接,则会打开连接但是消息永远不会收到。但是,可以从React中发送消息。

In "normal" JS this returns data from the server, if I use the same within React the connection gets opened but the message is never received. However messages can be sent from within React.

socket.addEventListener('message', function (event) {

        console.log('Message from server ', event.data);

  });


推荐答案

你应该能够创建一个本机模块以方便这个功能。

You should be able to create a native module to facilitate this functionality.

请查看此处的文档: https://facebook.github.io/react-vr/docs/native-modules.html

一旦你有了创建了你的模块并将它链接到client.js你可以将它导入你的组件并将其用作react vr和你的套接字实现之间的通信层。

Once you have created your module and linked it up in client.js you can import it into your components and use it as a communication layer between react vr and your sockets implementation.

要做这个,在你的 init 函数中 client.js 添加

To do this, within your init function in client.js add

const socketsModule = new SocketsModule();

然后在新导入或该文件中你自己可以添加:

then either in a new import or in that file itself you can add:

export class SocketsModule extends Module {
  constructor() {
    super('SocketsModule');
  }

  init() {
  }

  customMethod() {
    // Do fun stuff here
  }

}

然后在您的反应VR组件中,您希望调用这些方法首先包括这个新模块:

Then inside your react VR component you wish to call these methods you first include this new module:

const SocketsModule= NativeModules.SocketsModule;

然后你可以从该组件中访问它的方法:

Then you can access its methods from within that component:

SocketsModule.customMethod();

这篇关于从页面JS中访问React对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆