当我在GeneralNav中单击菜单时,可以成功在true或false之间切换。
此menuState再次通过HomePage成功传递给了Overlay。
尽管我无法切换“覆盖”中的正确类以隐藏或显示菜单。有人可以向我解释一个正确的工作流程,以便在EasyFlexCol组件上添加类以显示或隐藏它吗?现在被卡住了一段时间。
谢谢!
class GeneralNav extends Component {
render() {
return (
<div
className="nav-burger-box menu-action"
onClick={this.props.toggleMenu}
>
<div className="nav-burger-top" />
<div className="nav-burger-bottom" />
</div>
);
}
}
class HomePage extends Component {
state = {
showMenu: false
};
toggleMenu = e => {
e.preventDefault();
this.setState(state => ({ showMenu: !state.showMenu }));
};
render() {
return (
<React.Fragment>
<OverlayMenu menuState={this.state.showMenu}/>
<HeaderFullscreen />
</React.Fragment>
);
}
}
class OverlayMenu extends Component {
state = {
showMenu: "overlay-menu-wrapper bg-color-dark overlay-menu-wrapper display-block",
hideMenu: "overlay-menu-wrapper bg-color-dark overlay-menu-wrapper"
};
render() {
let menuState = this.props.menuState
console.log(menuState)
return (
<EasyFlexCol style={"here I want to add the right class to show or hide the overlay menu"}>
</EasyFlexCol>
);
}
}
答案 0 :(得分:0)
渲染时使用三元运算符。
class OverlayMenu extends Component {
render() {
const showHide= { // Assuming that strings below are valid CSS class names
showMenu: "overlay-menu-wrapper bg-color-dark overlay-menu-wrapper display-block",
hideMenu: "overlay-menu-wrapper bg-color-dark overlay-menu-wrapper"
};
let menuState = this.props.menuState
console.log(menuState)
return (
<EasyFlexCol className={menuState ? showHide.showMenu : showHide.hideMenu}>
</EasyFlexCol>
);
}
}
或者,您可以动态组成<EasyFlexCol/>
组件的样式
class OverlayMenu extends Component {
render() {
style={ display: 'block' }
let menuState = this.props.menuState
return (
<EasyFlexCol className={'some-default-class'} style={menuState ? style : {}}>
</EasyFlexCol>
);
}
}
两个示例均假设<EasyFlexCol/>
具有className
属性或style
属性。
答案 1 :(得分:0)
您可以像这样使用三元运算:
i.e,如果menuState为true,则显示showMenu,否则反之亦然
<EasyFlexCol className={menuState ? showHide.showMenu : showHide.hideMenu}>
</EasyFlexCol>
这是您推荐的有效示例:https://stackblitz.com/edit/react-wj49ol