调整标题onscroll React

时间:2018-05-25 02:00:35

标签: javascript reactjs

我需要在反应中基本上重写这个codepen。  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);

2 个答案:

答案 0 :(得分:3)

一个简单的实现包括

  1. 将scroll事件侦听器添加到componentDidmount,
  2. 将班级更改为className,
  3. 将html添加到render()
  4. 包括css
  5. 我在codesandbox.io

    为您创建了相同的内容

答案 1 :(得分:0)

好的,这是我的尝试。不确定它是否能正常工作但它会让你大致了解如何在反应中构建它。

//Create a navbar component
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.

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

  componentWillUnmount(){
    () => {
      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 >
  )
}