我正在尝试弄清楚当子组件状态改变时如何将样式设置为父组件
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中使用嵌套的绝对路由,如下所示
<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并在内容标记中呈现它的组件时,没有问题。
我需要给它全宽,并将侧栏显示设置为none,而侧栏已经呈现在容器组件中,我无法在子组件中控制它-以常规方式
我正在寻找一种能够在home组件中处理它的方法。
发布于 2016-03-31 04:15:15
您可以在子组件的道具中添加函数。当您需要更改父样式时,您可以在子组件中调用此函数。此函数将更改父组件的状态并更改其样式。
示例:
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'));发布于 2016-03-31 19:18:14
您可以在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将允许您在组件更新时更新状态
https://stackoverflow.com/questions/36318643
复制相似问题