我是 React 新手,我正在尝试构建一个包含“侧边栏幻灯片”的独立标头组件。我使用 state 来应用 CSS 将侧边栏滑入/滑出:
constructor() {
super();
this.state = {
sideBar: false
}
}
handleSidebar() {
this.setState({
sideBar: !this.state.sideBar
});
}
render() {
return(
<header>
<ul style={this.state.sideBar ? {'transform': 'translateX(0%)'} : null}></ul>
<button onClick={this.handleSidebar.bind(this)}></button>
</header>
)
这可以完成滑动侧边栏的工作,但是一旦侧边栏打开,我想通过应用来锁定主体上的滚动overflow:hidden
to the <body>
。然而自从<body>
在 React 之外,我想知道如何访问该标签?
链接到 Codepen https://codepen.io/hollow3d/pen/OjKByb
Use document.body
设置您需要的样式。确保您可以访问document
准备好后,将代码放入componentWillMount
。您应该在卸载组件后重置样式componentWillUnmount
.
componentWillMount() {
document.body.style.overflow = "hidden";
}
componentWillUnmount() {
document.body.style.overflow = "visible"; // or restore the original value
}
在您发表评论后,我意识到您需要在打开侧边栏后设置样式。这里有一些注意事项:
- 不要使用
this.state
in setState
. setState
是异步的,因此您应该使用可选的prevState
参数来访问先前的状态对象。
- 您可以使用可选的第二个参数
setState
这是一个函数,在状态更新后调用。在此功能中您可以设置正文的样式。
- You can
bind
构造函数中的函数。
- 在构造函数中传递
props
到基本构造函数(super(props)
).
- Rename
sideBar
to isSideBarOpen
。这是一个更具描述性的名称。
这是最终的代码:
constructor(props) {
super(props);
this.state = {
isSideBarOpen: false
};
this.toggleSideBar.bind(this);
}
updateBodyStyles() {
if (this.state.isSideBarOpen) {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "visible";
}
}
toggleSideBar() {
this.setState((prevState) => {
return { isSideBarOpen: !prevState.isSideBarOpen }
}, this.updateBodyStyles);
}
render() {
return (
<header>
<ul style={this.state.isSideBarOpen? {'transform': 'translateX(0%)'} : null}></ul>
<button onClick={this.toggleSideBar}></button>
</header>
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)