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

Javascript 如何根据其子组件状态更改父组件样式元素?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我正试图找出如何在子组件状态更改时为父组件设置样式 考虑一个场景,其中包含一个包含菜单和边栏的容器组件作为静态元素。 子组件。单击菜单时,其相应的组件将作为子组件渲染 我使用嵌套绝对路由和react路由器,如下所示 <Route component={ home } > <Route path="menu-1" component={ menu-1 } /> <Route path="menu-2" component={ men

我正试图找出如何在子组件状态更改时为父组件设置样式
考虑一个场景,其中包含一个包含菜单和边栏的容器组件作为静态元素。 子组件。单击菜单时,其相应的组件将作为子组件渲染

我使用嵌套绝对路由和react路由器,如下所示

    <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组件中,我有如下内容:

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

    </div>

{this.props.children}
正如您所看到的,我无法将回调函数传递给子组件 对于menu-1、menu-2,我没有问题,但是在单击menu-3并在内容标签中呈现其组件时,
我需要为其提供全宽,并将侧栏显示设置为“无” 虽然侧栏已在容器组件中渲染,但我无法在子组件中以常规方式控制它


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

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

例如:

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'));
类父级扩展React.Component{
构造函数(道具、上下文){
超级(道具、背景);
此.state={
背景颜色:“黄色”
}
}
onChangeStyle(背景色){
这是我的国家({
背景色:背景色
})
}
render(){
返回
}
}
子类扩展了React.Component{
onClick(){
这个.props.onChangeParentStyle('red');
}
render(){
返回
更改父样式
}
}
React.render(,document.getElementById('container');

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

componentWillMount(){
 let propPlainUrl = /[a-zA-Z]+/g.exec(this.props.location.pathname);
               this.setState({
                  activeMenu: menuItems.indexOf(propPlainUrl[0]) + 1
            });
您可以使用根据所选的布线菜单设置活动关键点的初始值

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

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

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


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

谢谢您的详细回答,@Alesandr实际上我知道回调函数,但我的情况有所不同,我已更新了问题,您可以使用React.cloneElement向子级添加道具。