Jan*_*kow 7 html javascript css reactjs
我是 React 的新手,我正在尝试构建一个包含“侧边栏中的幻灯片”的独立 Header 组件。我使用 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>
)
Run Code Online (Sandbox Code Playgroud)
这在滑动侧边栏方面可以完成工作,但是一旦侧边栏打开,我想通过应用overflow:hidden到<body>. 但是由于<body>在 React 之外,我想知道如何访问标签?
Dáv*_*nár 10
使用document.body设置您需要的样式。确保你document准备好后访问,所以把代码放在componentWillMount. 卸载componentWillUnmount.
componentWillMount() {
document.body.style.overflow = "hidden";
}
componentWillUnmount() {
document.body.style.overflow = "visible"; // or restore the original value
}
Run Code Online (Sandbox Code Playgroud)
在您发表评论后,我意识到您需要在打开侧边栏后设置样式。这里有一些注意事项:
this.state在setState. setState是异步的,因此您应该使用可选prevState参数来访问前一个状态对象。setState它是一个函数,并在状态更新后调用。在此功能中,您可以设置主体的样式。bind在构造函数中使用该函数。props给基础构造函数 ( super(props))。sideBar为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>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13649 次 |
| 最近记录: |