2017-10-19 186 views
0

我需要從HomeScreen.js更新BackGround.js的狀態。目前我採取的格式爲JSON:React另一個組件的本機設置狀態

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

作爲套接字的參數。從那裏我使用導航參數來確定要導航到哪個組件。我想從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

如果使用React Navigation,我假設你是,可以通過使對象作爲傳遞一個道具導航目標您的navigate()調用中的第二個參數。例如:

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

媒體屬性於是將在this.props.navigation.state.params.media屬性目標組件可用。

此代碼尚未經過測試,但應該可以工作。

+0

這是完美的謝謝! –

+0

很高興我能幫到你。 –