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>
);
}
}
這是完美的謝謝! –
很高興我能幫到你。 –