调整标题滚动react

IT技术 javascript reactjs
2022-07-16 00:59:09

我需要在react中基本上重写这个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个回答

一个简单的实现将包括

  1. 将滚动事件侦听器添加到 componentDidmount,
  2. 将类更改为类名,
  3. 将 html 添加到 render()
  4. 包括CSS

我在codesandbox.io中为您创建了相同的内容

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

//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 >
  )
}