访问< body>来自React [英] Access <body> from React
问题描述
我是React的新手,我正在尝试构建一个包含侧边栏中的幻灯片"的独立Header组件.我使用状态来应用CSS来滑动边栏进/出:
I'm new to React and I am trying to build a standalone Header component containing a 'slide in sidebar'. I used state to apply CSS to slide the sidebar in/out:
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
应用于< body>来锁定主体上的滚动
.但是,由于< body>
在React之外,所以我想知道如何访问标签?
This does the job in terms of sliding the sidebar, but once the sidebar is open, I would like to lock scroll on body by applying overflow:hidden
to the <body>
. However since <body>
is outside of React, I was wondering how it's possible to access the tag?
推荐答案
使用 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
.这是一个更具描述性的名称.
- Don't use
this.state
insetState
.setState
is asynchronous, therefore you should use the optionalprevState
parameter to access the previous state object. - You could use the optional second parameter of
setState
which is a function and is called after the state is updated. In this function you could set the styles of the body. - You can
bind
the function in the constructor. - In the constructor pass the
props
to the base constructor (super(props)
). - Rename
sideBar
toisSideBarOpen
. 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>
)
这篇关于访问< body>来自React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!