且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问< body>来自React

更新时间: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:

  1. 请勿在 setState 中使用 this.state . setState 是异步的,因此您应该使用可选的 prevState 参数访问先前的状态对象.
  2. 您可以使用 setState 的可选第二个参数,该参数是一个函数,在状态更新后调用.在此功能中,您可以设置身体的样式.
  3. 您可以在构造函数中 bind 该函数.
  4. 在构造函数中,将 props 传递给基本构造函数( super(props)).
  5. sideBar 重命名为 isSideBarOpen .这是一个更具描述性的名称.
  1. Don't use this.state in setState. setState is asynchronous, therefore you should use the optional prevState parameter to access the previous state object.
  2. 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.
  3. You can bind the function in the constructor.
  4. In the constructor pass the props to the base constructor (super(props)).
  5. Rename 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>
    )