2017-10-19 5 views
0

HomeScreen.js에서 BackGround.js의 상태를 업데이트해야합니다. 현재 JSON 형식을 사용합니다 :React 다른 구성 요소의 기본 설정 상태

{ 
"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

당신은 내가 당신이 가정 React Navigation를 사용하는 경우, 당신은 같은 객체를 전달하여 탐색 대상에 소품을 전달할 수 있습니다 navigate() 호출의 두 번째 매개 변수 예를 들면 :는

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

미디어 속성은 그 속성에 this.props.navigation.state.params.media 타겟 컴포넌트로 제공 될 것이다.

이 코드는 테스트되지 않았지만 정상적으로 작동합니다.

+0

이것은 완벽한 감사입니다! –

+0

기꺼이 도와 드리겠습니다. –

관련 문제