React组件滚动事件未在较小的窗口大小上触发

时间:2018-09-20 18:35:00

标签: javascript reactjs

我有一个导航栏,它将在向下滚动窗口时更改其css类,然后在返回顶部时更改为其原始类。但是,它确实希望在窗口低于1100px时触发。 任何帮助将不胜感激。

import React, { Component } from 'react';


import NavBar from './NavBar';
import DropDown from './DropDown';

class HeaderNavigation extends Component{

  constructor(props) {
      super(props);

      this.state = {
        dropDownOpen: false,
        isTop: true
      };
      this.onScroll = this.onScroll.bind(this);
    }

    componentDidMount() {
      window.onscroll = () => {
        const isTop = window.pageYOffset < 10 || document.documentElement.scrollTop < 10;
        console.log(isTop);
        if (isTop !== this.state.isTop) {
          this.onScroll(isTop);
        }
      }
    }

    onScroll(isTop) {
      this.setState({ isTop });
    }

dropdownToggleClickHandler = () => {
  this.setState((prevState) => {
    return {dropDownOpen: !prevState.dropDownOpen};
  });
};

render() {
    let dropDown;

    if(this.state.dropDownOpen){
      dropDown = <DropDown show = {this.state.dropDownOpen}/>
    }

  return (
    <div>
      <NavBar
      dropDownClickHandler = {this.dropdownToggleClickHandler}
      show = {this.state.dropDownOpen}
      classname = {this.state.isTop ? 'dm-website-navbar' : 'dm-website-navbar-scroll'}
      sourceUrl = {this.state.isTop ? 'assets/images/dm_white_logo_medium.png' : 'assets/images/dm_blue_logo_medium.png'}
    />
      {dropDown}
    </div>
  );
}
}


export {HeaderNavigation};

0 个答案:

没有答案