[英]React Native setting state of another Component
我需要從HomeScreen.js更新BackGround.js的狀態。 目前,我采用以下格式的JSON:
{
"navigate": "background",
"media": "red",
"sound_bool": "false",
"sound": ""
}
作為套接字的參數。 從那里,我使用Navigation參數確定要導航到的組件。 我想將媒體參數從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>
);
}
}
如果您使用的是React Navigation (我假設是這樣),則可以通過將對象作為您的navigation navigate()
調用中的第二個參數來傳遞prop到導航目標。 例如:
case 'image':
this.props.naviagtion.navigate('IS',{ media: media });
break;
然后,媒體屬性將在this.props.navigation.state.params.media
屬性的目標組件中this.props.navigation.state.params.media
。
該代碼尚未經過測試,但可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.