最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resize Header onscroll React - Stack Overflow

programmeradmin2浏览0评论

I need to basically rewrite this codepen in react.

function resizeHeaderOnScroll() {
 const distanceY = window.pageYOffset || 
 document.documentElement.scrollTop,
 shrinkOn = 200,
 headerEl = document.getElementById('js-header');

if (distanceY > shrinkOn) {
   headerEl.classList.add("smaller");
   } else {
    headerEl.classList.remove("smaller");
   }
 }

window.addEventListener('scroll', resizeHeaderOnScroll);

I need to basically rewrite this codepen in react. https://codepen.io/lili2311/pen/dJjuL

function resizeHeaderOnScroll() {
 const distanceY = window.pageYOffset || 
 document.documentElement.scrollTop,
 shrinkOn = 200,
 headerEl = document.getElementById('js-header');

if (distanceY > shrinkOn) {
   headerEl.classList.add("smaller");
   } else {
    headerEl.classList.remove("smaller");
   }
 }

window.addEventListener('scroll', resizeHeaderOnScroll);
Share Improve this question asked May 25, 2018 at 2:00 zeddyzeddy 311 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

A simple implementation would include

  1. adding the scroll event listener to ponentDidmount,
  2. changing class to className,
  3. adding html to render()
  4. including the css

I have created the same for you in codesandbox.io

Ok here is my try. Not sure if it going to work properly or not but It will give you a general idea how to build it in react.

//Create a navbar ponent
class Navbar extends Component {
  constructor() {
    super();

    //In the state you can keep track of the class you want to add to the element
    this.state = {
      class: "" //For now its empty or you can give it a default class.
    }
  }

  //use the lifecycle methods to trigger the getWindowHeight method.

  ponentDidMount(){
     () => {
      window.addEventListener('scroll', this.getWindowHeight);
     }
  }

  ponentWillUnmount(){
    () => {
      window.removeEventListener('scroll', this.getWindowHeight);
    }
  }

  //then create the method
  getWindowHeight = () {

    const distanceY = window.pageYOffset ||
      document.documentElement.scrollTop
    const shrinkOn = "200px";

    //Now In the condition change the state to smaller so if the condition is true it will change to smaller otherwise to default state
    if (distanceY > shrinkOn) {
      this.setState({
        class: "smaller"
      })
    }
  }
  
render() {
  return (
    //Now in the element you can add the state to the class as well as add event to the onScroll
    <navbar className={this.state.class} >
    </navbar >
  )
}

发布评论

评论列表(0)

  1. 暂无评论