更新时间:2022-11-30 11:18:36
使用 document.body
设置所需的样式.确保准备好访问 document
后,将代码放在 componentWillMount
中.在 componentWillUnmount
中卸载组件后,应重置样式.
Use document.body
to set the styles you need. Make sure you access document
after it's ready, so put the code in componentWillMount
. You should reset the styles after unmounting the component in componentWillUnmount
.
componentWillMount() {
document.body.style.overflow = "hidden";
}
componentWillUnmount() {
document.body.style.overflow = "visible"; // or restore the original value
}
发表评论后,我意识到您需要在打开侧边栏后设置样式.这里有一些注意事项:
After your comment I realized that you need to set the styles after opening the sidebar. Here some notes:
setState
中使用 this.state
. setState
是异步的,因此您应该使用可选的 prevState
参数访问先前的状态对象. setState
的可选第二个参数,该参数是一个函数,在状态更新后调用.在此功能中,您可以设置身体的样式. bind
该函数. props
传递给基本构造函数( super(props)
). sideBar
重命名为 isSideBarOpen
.这是一个更具描述性的名称.this.state
in setState
. setState
is asynchronous, therefore you should use the optional prevState
parameter to access the previous state object. setState
which is a function and is called after the state is updated. In this function you could set the styles of the body.bind
the function in the constructor.props
to the base constructor (super(props)
).sideBar
to isSideBarOpen
. It is a more descriptive name.这是最终代码:
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>
)