如何根据其子组件状态更改父组件样式元素?

Fak*_*bdi 5 javascript reactjs react-router

我试图弄清楚如何在子组件状态更改时为父组件设置样式,请
考虑一个场景,其中我们有一个包含菜单和侧栏作为其静态元素和子组件的容器组件。单击菜单时,它的相应组件将呈现为子组件。

我正在使用带有反应路由器的嵌套绝对路由,如下所示

    <Route component={ home } >
       <Route path="menu-1" component={ menu-1 } />
       <Route path="menu-2" component={ menu-2 } />
       <Route path="menu-3" component={ menu-3 } />
Run Code Online (Sandbox Code Playgroud)

在 home 组件中,我有以下内容:

    <div className='root'>
        <menuComponent />
        <sideBarComponnent />
        {this.props.children}

    </div>
Run Code Online (Sandbox Code Playgroud)

如您所见,我无法将回调函数传递给 menu-1 和 menu-2 的子组件我没有问题,但是在单击 menu-3 并在内容标签中呈现它的组件时,
我需要给它全宽并将侧栏显示设置为无,而侧栏已在容器组件中呈现我无法以常规方式在子级内部控制它

我正在寻找一种可以在 home 组件中处理它的方法

小智 1

您可以在子组件的 props 中添加功能。当您需要更改父样式时,您可以在子组件中调用此函数。此函数将更改父组件的状态并更改其样式。

例子:

class Parent extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            backgroundColor: 'yellow'
        }
    }

    onChangeStyle(backgroundColor) {
        this.setState({
            backgroundColor: backgroundColor
        })
    }

    render() {
        return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}>
            <Child onChangeParentStyle={this.onChangeStyle.bind(this)}/>
        </div>
    }
}

class Child extends React.Component {
    onClick() {
        this.props.onChangeParentStyle('red');
    }
    render() {
        return <span onClick={this.onClick.bind(this)} style={{background: 'white', cursor: 'pointer'}}>
            Change parent style
        </span>
    }
}

React.render(<Parent />, document.getElementById('container'));
Run Code Online (Sandbox Code Playgroud)

JSFiddle 上的示例