我正在尝试从不包含 websocket 的组件向我的 websocket 服务器发送答案。我的 Websocket 服务器如下所示:
componentDidMount() {
var ws = new WebSocket('ws:// URL');
ws.onmessage = this.handleMessage.bind(this);
...
}
如何将“var ws”传递给另一个类或组件。或者是否可以使 websocket 全局可访问? 非常感谢您的帮助!
最佳答案
我在 stackoverflow 中的这个问题的帮助下找到了解决方案:
访问:
React native: Always running component
我创建了一个新类 WebsocketController,如下所示:
let instance = null;
class WebsocketController{
constructor() {
if(!instance){
instance = this;
}
this.ws = new WebSocket('ws://URL');
return instance;
}
}
export default WebsocketController
然后在我需要 websocket 的其他类(class)中,我只是这样调用它:
let controller = new WebsocketController();
var ws = controller.ws;
关于javascript - React Native Websocket外部访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684983/