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

How to change parent-component style element according to its child-component state?

本文关键字:组件 样式 元素 何根 状态      更新时间:2023-09-26

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

我使用嵌套的绝对路由和反应路由器如下

    <Route component={ home } >
       <Route path="menu-1" component={ menu-1 } />
       <Route path="menu-2" component={ menu-2 } />
       <Route path="menu-3" component={ menu-3 } />

在家庭组件内部,我有如下内容:

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

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

我正在寻找一种能够在主组件中处理它的方法

您可以在子组件的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'));

JSFiddle 示例

您可以在组件WillMount中使用this.props.location.pathname,如下所示:

componentWillMount(){
 let propPlainUrl = /[a-zA-Z]+/g.exec(this.props.location.pathname);
               this.setState({
                  activeMenu: menuItems.indexOf(propPlainUrl[0]) + 1
            });

您可以使用componentWillMount根据选择的路线菜单设置活动钥匙的初始值

上面的代码在home组件的初始渲染时只解决了一次问题但是,如果您想在单击菜单事件中更新组件的同时保持程序的更新,该怎么办?

您可以使用相同的代码,但略有更改,如下所示:

componentWillReceiveProps(nextProps){
     let propPlainUrl = /[a-zA-Z]+/g.exec(nextProps.location.pathname);
     this.setState({
       activeMenu: menuItems.indexOf(propPlainUrl[0]) + 1
     });
   }

```

componentWillReceiveProps将允许您更新组件更新的状态