我需要从主屏幕.js更新BackGround.js的状态。目前我采用以下格式的 JSON:
{
"navigate": "background",
"media": "red",
"sound_bool": "false",
"sound": ""
}
作为套接字的参数。从那里,我使用 navigate 参数来确定要导航到哪个组件。我想将媒体参数从 JSON 发送到正在导航到的组件,以便更改状态。我应该怎么做?
主屏幕.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>
);
}
}
背景.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>
);
}
}
如果您使用的是 React Navigation(我假设您是这样),您可以通过将对象作为navigate()
调用中的第二个参数传递到导航目标。 例如:
case 'image':
this.props.naviagtion.navigate('IS',{ media: media });
break;
然后,media 属性将在 this.props.navigation.state.params.media
属性的目标组件中可用。
此代码尚未经过测试,但它应该可以工作。