React另一个Component的Native设置状态

时间:2017-10-19 16:39:23

标签: javascript facebook react-native

我需要从HomeScreen.js更新BackGround.js的状态。目前我采用格式的JSON:

{
"navigate": "background",
"media": "red",
"sound_bool": "false",
"sound": ""
}

作为套接字的参数。从那里我使用navigate参数来确定要导航到的组件。我想将媒体参数从JSON发送到正在导航到的组件,以便更改状态。我应该怎么做呢?

HomeScreen.js

import React, { Component } from 'react';
import {Image, Text, StyleSheet, Button, View, Dimensions, Vibration} from 'react-native';
import {StackNavigator} from 'react-navigation'

console.ignoredYellowBox = [
    'Setting a timer'
]


const io = require('socket.io-client');
let server = 'http://redacted:3000';
let socket = io(server, {
  transports: ['websocket']
});


export default class HomeScreen extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      backgroundColor: 'orange',
    }; 


  }
  static navigationOptions = {
    header: null
  }
  render(){
    const { navigate } = this.props.navigation;
    socket.on('json emission', json => {
      var json_dump = JSON.parse(json);
      var navi = json_dump.navigate;
      var media = json_dump.media;
      //parse JSON and send commands from here
      switch(navi){
      case 'image':
        navigate('IS');
        break;
      case 'background':
        navigate('BG');
        break;
      case 'buttons':
        navigate('BB');
        break;
      default:
        console.log("Error invalid navigation command: " + navi);
        break;
      }
    });
      return (
      <View style={{backgroundColor: this.state.backgroundColor, flex: 1}}>

      </View>
      );
    }
  }

BackGround.js

import React, { Component } from 'react';
import {Image, Text, StyleSheet, Button, View, Dimensions, Vibration} from 'react-native';
import {StackNavigator} from 'react-navigation'

export default class BackGround extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      backgroundColor: 'green'
    }; 
  }
  static navigationOptions = {
    header: null
 }
 render(){
  const { navigate } = this.props.navigation;
 return (
 <View style={{backgroundColor: this.state.backgroundColor, flex: 1}}>
 </View>
 );
}
}

1 个答案:

答案 0 :(得分:1)

如果您使用的是React Navigation,我认为您可以通过将对象作为navigate()调用中的第二个参数传递给导航目标。例如:

case 'image':
    this.props.naviagtion.navigate('IS',{ media: media });
    break;

然后,媒体属性将在this.props.navigation.state.params.media属性中的目标组件中可用。

此代码尚未经过测试,但应该可以使用。