对于像我这样的人,在此问题上tum绊绊,寻找如何将socket.io与react native集成在一起。
由于React Native短时间内支持websocket,因此您现在可以使用Socket.io轻松地设置Web套接字。您要做的只是以下内容
- npm install socket.io-client
- 首次进口本机
- 分配
window.navigator.userAgent = 'react-native';
- 导入socket.io-client / socket.io
- 在构造函数中分配
this.socket = io('localhost:3001', {jsonp: false});
因此,在npm安装socket.io-client之后,它看起来应该像这样:
import React from 'react-native';// ... [other imports]import './UserAgent';import io from 'socket.io-client/socket.io';export default class App extends Component { constructor(props) { super(props); this.socket = io('localhost:3001', {jsonp: false}); } // now you can use sockets with this.socket.io(...) // or any other functionality within socket.io! ...}然后在“ UserAgent.js”中:
window.navigator.userAgent = 'react-native';
注意:因为悬挂了ES6模块的导入,所以我们不能在与react-native和socket.io导入相同的文件中进行userAgent分配,因此是单独的模块。
编辑:
上面的解决方案应该可以,但是在这种情况下,请不要尝试创建单独的socketConfig.js文件。在其中导入任何需要的东西,包括
const io =require('socket.io-client/socket.io');并且window.navigator.userAgent = 'react-native';需要socket.io-
client之前。然后,您可以在此处连接套接字,并将所有侦听器放在一个位置。然后,可以将操作或功能导入配置文件,并在侦听器接收数据时执行。



