响应本机父子通信和返回值

时间:2016-12-14 16:46:08

标签: reactjs react-native

我是反应原生环境的初学者。我希望通过本机来理解父母的孩子沟通。

  1. 家长会将一个号码传递给孩子 - 例如,父母将“2”传递给孩子。

  2. Child将拥有一个处理函数,该函数多次使用相同的数字2次,并将结果返回给父级。 - 例如2 * 2并返回

  3. parent将调用子函数并查看输出是否正确并在父容器上打印结果

  4. 如果我在c ++或java等编程语言中完成此操作。

    *

  5. 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文件做出反应,一个用于父项,一个用于孩子,并向我显示通信。

    谢谢

1 个答案:

答案 0 :(得分:7)

通过将回调/处理程序传递给子组件来完成,这是一个示例。我没有测试过它。

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