这是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);