首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据其子组件状态更改父组件样式元素?

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

Stack Overflow用户
提问于 2016-03-31 04:03:40
回答 2查看 7.2K关注 0票数 5

我正在尝试弄清楚当子组件状态改变时如何将样式设置为父组件

代码语言:javascript
复制
 consider a scenario in which we have a container component containing menu and side bar as its static elements plus      child-component. while clicking the menu, it's corresponding component will render as child-component.

我在react-router中使用嵌套的绝对路由,如下所示

代码语言:javascript
复制
    <Route component={ home } >
       <Route path="menu-1" component={ menu-1 } />
       <Route path="menu-2" component={ menu-2 } />
       <Route path="menu-3" component={ menu-3 } />

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

代码语言:javascript
复制
    <div className='root'>
        <menuComponent />
        <sideBarComponnent />
        {this.props.children}

    </div>

正如您所看到的,我不能将回调函数传递给menu-1,menu-2的子组件,但在单击menu-3并在内容标记中呈现它的组件时,没有问题。

我需要给它全宽,并将侧栏显示设置为none,而侧栏已经呈现在容器组件中,我无法在子组件中控制它-以常规方式

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

EN

回答 2

Stack Overflow用户

发布于 2016-03-31 04:15:15

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

示例:

代码语言:javascript
复制
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'));

Example on JSFiddle

票数 1
EN

Stack Overflow用户

发布于 2016-03-31 19:18:14

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

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

您可以使用componentWillMount根据所选的路由菜单设置活动键的初始值

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

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

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

componentWillReceiveProps将允许您在组件更新时更新状态

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36318643

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档