设置React组件以监听socket.io [英] Set up React component to listen to socket.io
问题描述
我希望我的React组件监听来自socket.io的事件.如果我的HTML文件包括:
I want my React component to listen to events from socket.io. My code works if I have the HTML files include:
< script src ="socket.io/socket.io.js"></script>
,然后组件的Constructor()具有:
and then the component's constructor() has:
this.socket = io();//eslint-disable-line no-undef
HTML文件从我的Express服务器检索正确的socket.io客户端代码,一切正常.
The HTML file retrieves the proper socket.io client code from my Express server, and everything's fine.
但这感觉很俗气.我讨厌依靠全局窗口名称空间来查找io()函数.让React组件通过socket.io连接到服务器的最佳实践是什么?谢谢.
But this feels so cheesy. I hate to rely on the global window name space to find the io() function. What's the best practice for letting a React component connect through socket.io to the server? Thanks.
推荐答案
如果您使用的是Webpack或Browserify等捆绑程序,则可以使用
If you're using a bundler like Webpack or Browserify, you can use socket.io-client
.
例如:
const io = require('socket.io-client');
class MyComponent extends React.Component {
constructor(...args) {
super(...args);
this.socket = io();
}
...
}
这篇关于设置React组件以监听socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!