我如何添加类名正文向下滚动反应?

how can i add classname body scroll down react?

我想在向下滚动 100px 时,在 gatsby 反应上添加正文 className="showdiv"

我该怎么做?

我试试这个代码:

state = {
  isTop: true,
};

componentDidMount() {
  document.addEventListener('scroll', () => {
    const isTop = window.scrollY < 100;
    if (isTop !== this.state.isTop) {
        this.setState({ isTop })
    }
  });
}

class姓名

{this.state.isTop ? 'down' : 'up'}

但是我无法添加正文class。我想要新的和简单的想法..

谢谢

您可以像之前那样添加滚动侦听器,但是根据滚动位置 add/remove showChildDiv class 从正文中添加。

例子

class App extends React.Component {
  componentDidMount() {
    window.addEventListener("scroll", this.toggleBodyClass);
    this.toggleBodyClass();
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.toggleBodyClass);
  }

  toggleBodyClass = () => {
    if (window.scrollY < 100) {
      document.body.classList.add("showChildDiv");
    } else {
      document.body.classList.remove("showChildDiv");
    }
  };

  render() {
    return (
      <div
        style={{
          height: "1000px"
        }}
      />
    );
  }
}