将套接字传递给组件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将套接字传递给组件相关的知识,希望对你有一定的参考价值。
这是React Native 0.59 app的App.js
。
import React, {Component} from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Event from './src/components/event/Event.js';
import Chat from './src/components/chat/Chat.js';
import GLOBAL from "../../lib/global";
//socket.io
const socket = io(GLOBAL.BASE_URL, {
transports: ['websocket'],
jsonp: false
});
//create the navigator
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: Chat,
}
}, {
initialRouteName: "Event"
}
);
//export it as the root component
export default createAppContainer(navigator);
socket
需要传递到Chat
组件。由于只有使用socket
的Chat组件,我想将socket
作为道具而不是使用context
,它在许多组件之间共享数据。理想情况下,socket
可以像createStackNavigator
一样传递:
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: Chat, params: {socket: this.socket}
}
}, {
initialRouteName: "Event"
}
);
如何用React Native 0.59
做到这一点?
答案
我能想到的最简单的方法是创建一个新的组件,它将Chat组件和套接字作为prop返回。
例
import React, {Component} from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Event from './src/components/event/Event.js';
import Chat from './src/components/chat/Chat.js';
import GLOBAL from "../../lib/global";
//socket.io
const socket = io(GLOBAL.BASE_URL, {
transports: ['websocket'],
jsonp: false
});
const ChatWithSocket = () => (<Chat socket={socket} />)
//create the navigator
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: ChatWithSocket,
}
}, {
initialRouteName: "Event"
}
);
//export it as the root component
export default createAppContainer(navigator);
以上是关于将套接字传递给组件的主要内容,如果未能解决你的问题,请参考以下文章