如何在滚动事件中切换类以做出反应?

时间:2018-06-25 18:09:37

标签: javascript reactjs

如果在页面中滚动,我需要在元素上添加或删除类。我写了这样的代码来跟踪页面滚动:

export default class TestComponenet extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      scrolled: false
    }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  };

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  };

  handleScroll(event) {
    this.setState({srolled: true});
  };

  render() {
    return (
      <div className ={scrolled ? 'scrolling' : ''}></div>
    );
  }
}

但是我只能跟踪滚动,但不能动态切换类。

1 个答案:

答案 0 :(得分:1)

浏览器中没有真正的“滚动状态”。当用户滚动时,您会收到一个事件,然后结束。您可以设置一个超时时间,如果用户没有滚动,则将其设置为不滚动:

示例

class App extends React.Component {
  state = {
    scrolled: false
  };

  componentDidMount() {
    window.addEventListener("scroll", this.handleScroll);
  }

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

  handleScroll = event => {
    this.setState({ scrolled: true });

    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.setState({ scrolled: false });
    }, 200);
  };

  render() {
    const { scrolled } = this.state;

    return (
      <div
        className={scrolled ? "scrolling" : ""}
        style={{
          width: 200,
          height: 1000,
          backgroundColor: scrolled ? "blue" : "red"
        }}
      />
    );
  }
}
相关问题