React Native Child Parent communication

后端 未结 2 2223
庸人自扰
庸人自扰 2021-02-19 18:16

Parent Child communication seems no problem using pass props:

mainpage.ios.js code:

var OtherPage = require(\'./otherpage\');


        
2条回答
  •  -上瘾入骨i
    2021-02-19 18:41

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

    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 ;
      }
      
    }
    
    class Other extends Component {
      render() {
        const { data } = this.props;
        console.log(`Other Component Data is ${data}`);
        return (
           {this.props.onChange('Success!')} }>
            {data}
          
        );
      }
    }
    

    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 ;
      }
      
    }
    
    const Other = ({ data, onChange }) => {
      return (
           {onChange('Success!')} }>
            {data}
          
      );
    }
    

    EDIT These days you should probably only use functional components and hooks, there is much documentation on the React websites on this, but the idea is similar :-)

提交回复
热议问题