react-native父子通信并返回值

IT技术 reactjs react-native
2021-05-19 20:10:11

我是 React Native 环境的初学者。我想了解react-native中的父子交流。

  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.
  }

*

我在网上看过几个 react native 教程,但是,这个父子交流仍然不清楚。

有人可以编码 2 react native js 文件,一个给父母,一个给孩子,并向我展示交流。

谢谢

1个回答

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

父.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>
        );
    }
}

儿童.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" />)
    }
}

这些是一些推荐阅读以更好地理解react https://facebook.github.io/react/docs/thinking-in-react.html https://facebook.github.io/react/docs/lifting-state-up。 html