정상으로 돌아오다

1680 단어 React
기록해 두다
 BackTop.js 코드는 다음과 같습니다.
import React, { Component } from 'react'

class BackTop extends Component {
  constructor (props) {
    super(props)
    this.state = {
      show: false
    }
  }

  //           
  handleClick = () => {
    let scrollToTop = setInterval(function () {
      //                 Y  
      let pos = window.pageYOffset
      if (pos > 0) {
        //        
        if (pos - 20 < 0){
          window.clearInterval(scrollToTop)
        }
        window.scrollTo(0, pos - 20)
      } else {
        window.clearInterval(scrollToTop)
      }
    }, 4)
  }
  //      
  HandleScroll = () => {
    //           
    let scrollTop = window.scrollY
    //        400       ,    
    if (scrollTop > 400) {
      this.setState({
        show: true
      })
    } else {
      this.setState({
        show: false
      })
    }
  }
  componentDidMount = () => {
    window.addEventListener('scroll', this.HandleScroll)
  }
  componentWillUnmount = () => {
    window.removeEventListener('scroll', this.HandleScroll)
  }

  render () {
    return (
      
        {this.state.show ? 
: ''} ) } } export default BackTop

 

 style.scss代码如下:

.back-top{
  position: fixed;
  bottom: 100px;
  right: 20px;
  width: 58px;
  height: 97px;
  background: red;
  background-size: 100% 100%;
  transition: all .3s;
  &:hover{
    cursor: pointer;
    background: white;
    background-size: 100% 100%;
  }
}

좋은 웹페이지 즐겨찾기