React.js pass data between components flow

前提是你 提交于 2019-12-01 06:15:14

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 (
            <div>{this.props.show}
                <B show={this.state.show}/>
                <C handleChangeShow={this.changeShow.bind(this)} show={this.state.show}/>
            </div>
        )
    }
}

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 (
           <select onChange={this.handleChange.bind(this)}>
                <option value="0">hide</option>
                <option value="1">show</option>
           </select>
        )
    }
}

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

I tried to create the same scenario that u described, check the jsfiddle for working example.

jsfiddle : https://jsfiddle.net/mj8rsawh/

please comment on this if you want any other help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!