回到顶部

记录一下

 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%;
  }
}

 

你可能感兴趣的:(React)