【问题标题】:How to change parent-component style element according to its child-component state?如何根据子组件状态更改父组件样式元素?
【发布时间】:2016-07-19 00:51:27
【问题描述】:

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

我正在使用带有 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 } />

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

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

    </div>

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

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

    例子:

    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

    【讨论】:

    • 感谢您的详细回答,@Alesandr 其实我知道回调函数,但我的情况有些不同,我已经更新了问题
    • 你可以使用 React.cloneElement 给孩子添加道具。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 2018-02-25
      • 2016-12-21
      • 2020-12-31
      • 2021-01-12
      • 1970-01-01
      • 2017-11-27
      相关资源
      最近更新 更多