如何根据子组件的状态更改父组件样式元素
How to change parent-component style element according to its child-component state?
我正试图弄清楚如何在子组件状态更改时将样式设置为父组件
考虑一个场景,在该场景中,我们有一个容器组件,其中包含作为其静态元素的菜单和侧栏以及子组件。单击菜单时,它的相应组件将渲染为子组件。
我使用嵌套的绝对路由和反应路由器如下
<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将允许您更新组件更新的状态
相关文章:
- 使用jquery在react组件内部设置样式可以吗
- webpack样式加载器-在react组件上导入不同的样式,而无需重写
- 如何在react组件上应用css样式
- 如何根据子组件的状态更改父组件样式元素
- 如何通过css模块将样式应用于react组件
- 如何在HTML中设置React组件的样式
- 反应 - 组件样式不从道具更新
- 自动建议反应.js组件不会在渲染时更新输入样式
- 应用样式“;游标:指针”;所有具有onClick功能的React组件
- web组件如何尽快获得自己的样式(宽度等)
- 在React组件中呈现样式元素
- 注入样式标签+ angular组件计时
- 如何改变react组件的样式和类
- 基于父CSS状态的条件子动画(带有React的样式组件)
- ReactJS -内联样式不会在重新呈现组件时更新
- 在组件内部定义样式,但不要内联
- 样式化tomahawk上传文件组件
- Angular组件样式指南
- ExtJs 4:带有Ext.ux.upload插件的组件在以MVC样式重写后停止工作
- Angular2组件样式/css没有被浏览器应用在ngafterviewit中