React Native Child Parent通信 [英] React Native Child Parent communication

查看:92
本文介绍了React Native Child Parent通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用传递道具时,父子通信似乎没有问题:

Parent Child communication seems no problem using pass props:

mainpage.ios.js代码:

mainpage.ios.js code:

var OtherPage = require('./otherpage');
<OtherPage value={2}/>

然后在otherpage.ios.js上我可以使用this.props.value来使用变量但是如果我更新了otherpage.ios.js上的值,它是如何传达回mainpage.ios.js的?

Then on otherpage.ios.js I can utilise the variable using this.props.value but then if I update the value on otherpage.ios.js how does it get communicated back to the mainpage.ios.js?

推荐答案

你会传递一个回调,然后通过道具传递它,可能会利用componentWillReceiveProps钩子,因为你的设置变得更高级。

You would pass a callback then pass it through props, likely utilizing the componentWillReceiveProps hook as your setup gets more advanced.

如果你这样做很多,那么是的,你应该使用Flux或Redux或类似的。

If you are doing this alot then yes, you should be using Flux or Redux or similar.

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


class Main extends Component {

  constructor() {
    super();
    this.state = {
      data: 'default'
    }
  }

  onChange = (data) => {
    console.log(`Data changes to ${data} !`);
    this.setState({ data });
  }

  render() {
    const { data } = this.state;
    return <Other data={data} onChange={this.onChange}></Other>;
  }

}

class Other extends Component {
  render() {
    const { data } = this.props;
    console.log(`Other Component Data is ${data}`);
    return (
      <TouchableOpacity onPress={() => {this.props.onChange('Success!')} }>
        <Text style={{fontSize: 30}}>{data}</Text>
      </TouchableOpacity>
    );
  }
}

此外,如果您在了解状态时使用静态组件在辅助组件中不需要,您可以构建更多可重用的功能组件:

Additionally, if you utilize Static Components when you know state is not needed in the secondary component, you can build much more re-useable functional components:

class Main extends Component {

  constructor() {
    super();
    this.state = {
      data: 'default'
    }
  }

  onChange = (data) => {
    console.log(`Data changes to ${data} !`);
    this.setState({ data });
  }

  render() {
    const { data } = this.state;
    return <Other data={data} onChange={this.onChange}></Other>;
  }

}

const Other = ({ data, onChange }) => {
  return (
      <TouchableOpacity onPress={() => {onChange('Success!')} }>
        <Text style={{fontSize: 30}}>{data}</Text>
      </TouchableOpacity>
  );
}

这篇关于React Native Child Parent通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆