2016-12-14 30 views
1

我是一個初學者的反應原生環境。我想通過反應原生了解父母的孩子溝通。反應本地父親子通信和返回值

  1. 父母會將一個數字傳遞給孩子 - 例如父母給孩子傳遞「2」。

  2. 孩子將有一個處理函數,其倍數相同的數字2倍,並返回結果回父。 - 作爲例子2 * 2,返回

  3. 父母會打電話給孩子的功能,看看是否輸出,如果在父容器

  4. 正確的打印結果,如果我想在一個編程郎已經做到了這一點像C++或Java。

    *

parent.number = 2; 
    parent.result = child.getResult(parent.number); 
    if(parent.result == 4){ 
     Print "child return correct value"; 
    }else{ 
     child return wrong value. 
    } 

*

我見過幾個在線反應本土教程,但,還是這個父子溝通不清晰。

有人可以請代碼2反應原生js文件一個爲父母和一個爲孩子,並告訴我的溝通。

感謝

回答

3

它通過傳遞迴調/處理程序,子組件完成,下面是一個例子。我還沒有測試過它。

Parent.js

import React, { Component } from 'react'; 
import { Text, View } from 'react-native'; 
import Child from './Child.js'; 

export default class Parent extends Component { 
    constructor() { 
     super(); 
     this.state = { 
      result: 0 
     }; 
    } 

    getResponse(result){ 
     this.setState({result}); 
    } 

    render(){ 
     return (
      <View> 
       <Text>{this.state.result}</Text> 
       <Child num={2} callback={this.getResponse.bind(this)}> 
      </View> 
     ); 
    } 
} 

Child.js

import React, { Component } from 'react'; 
import { Button } from 'react-native'; 

export default class Child extends Component { 
    calc(){ 
     this.props.callback(this.props.num * 2); 
    } 

    render(){ 
     return (<Button onPress={() => this.calc()} title="Calc" />) 
    } 
} 

這些都是一些推薦閱讀更好地理解反應 https://facebook.github.io/react/docs/thinking-in-react.html https://facebook.github.io/react/docs/lifting-state-up.html