繁体   English   中英

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

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

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

我正在使用嵌套绝对路由与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 } />

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

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

    </div>

如您所见,我不能将回调函数传递给menu-1的子组件,menu-2我没有问题,但是在单击menu-3并将其组件显示在content标签中时,
我需要给它提供全宽并将边栏显示设置为无,而边栏已在容器组件中渲染,我无法以常规方式在子控件中控制它

我正在寻找一种可以在家庭组件内部处理它的方法

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

例:

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上的示例

您可以在componentWillMount中使用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将让您在组件更新时更新状态

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM