React.js pass data between components flow

后端 未结 2 838
天涯浪人
天涯浪人 2021-01-13 05:35

I have created three basic components.

A renders both the components B and C B is like header containg tabs 1,2,3 C is the first page on which there are two forms, o

2条回答
  •  青春惊慌失措
    2021-01-13 06:22

    You will need to add your state to parent component here it would be A component then pass a function to change your states to B and C to change your state on A like below

    class A extends React.Component {
        constructor(props) {
            super();
            this.state = {
                show : '1',
            };
        }
        changeShow(show){
            this.setState({show: show});
        }
        render() {
            return (
                
    {this.props.show}
    ) } }

    Now you have access to show state in your child components and can change it from them for example in C

    class C extends React.Component {
        handleChange({target}){
            this.props.handleChangeShow(target.value)
        }
        render() {
            return (
               
            )
        }
    }
    

    Now you have access to show state in B

    class B extends React.Component {
    
        render() {
            return (
               {this.props.show}
            )
        }
    }
    

    It wasn't clear enough what were you trying to do in your example so I tried to give a example how to pass state between child component in a general sense. I hope it would be useful enough

提交回复
热议问题