问题
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'
}
);
Edit: Server updates are coming via a Websockets connection, but from within React the messages are not being received, only in the "normal" JS.
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);
});
回答1:
You should be able to create a native module to facilitate this functionality.
Check out the documentation around this here: https://facebook.github.io/react-vr/docs/native-modules.html
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.
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
}
}
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();
来源:https://stackoverflow.com/questions/47656179/access-react-object-from-within-page-js