将套接字传递给组件

问题描述 投票:0回答:1

这是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做到这一点?

react-native react-navigation
1个回答
3
投票

我能想到的最简单的方法是创建一个新的组件,它将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); 
© www.soinside.com 2019 - 2024. All rights reserved.