实现吸顶效果组件

  import React, { Component } from 'react';
  //引入由styled-components创建的样式组件
  import {ScrollToTopWrapper} from './ScrollToTopStyleComponents' 
  class ScrollToTop extends Component {
    constructor(props) {
      super(props)
 
      //show为true时回到顶部按钮显示,false时隐藏
      this.state = ({
        show: false
      })
      //将函数里的this指向绑定到当前组件,也就是组件ScrollToTop
      this.changeScrollTopShow = this.changeScrollTopShow.bind(this);
      this.scrollToTop = this.scrollToTop.bind(this);
    }
    //挂载事件监听
    componentDidMount() {
      window.addEventListener('scroll', this.changeScrollTopShow)
    }
    //卸载事件监听
    componentWillUnmount() {
      window.removeEventListener('scroll', this.changeScrollTopShow)
    }
    render() {
      const { show } = this.state;
      return(
        //ScrollToTopWrapper是一个由styled-components定义的样式组件,其本质
        //是一个div标签
        <ScrollToTopWrapper>
          {
            // 逻辑与符号左边的show为true时返回右边的html标签
            show && 
            <div 
              className = "scrollTop" 
              onClick = {this.scrollToTop}
            >
              <span className ="fa fa-arrow-up"></span>
            </div>
          }
        </ScrollToTopWrapper>
 
      )
    }
    //控制show的状态从而控制回到顶部按钮的显示和隐藏
    changeScrollTopShow() {
      if (window.pageYOffset < 400) {
        this.setState({
          show: false
        })
      }else {
        this.setState({
          show: true
        })
      }
    }
    //添加动画效果
    scrollToTop() {
      const scrollToTop = window.setInterval(() => {
        let pos = window.pageYOffset;
        if ( pos > 0 ) {
          window.scrollTo( 0, pos - 20 );
        } else {
          window.clearInterval( scrollToTop );
        }
      }, 1);
    }
  }
 
  //导出组件
  export default ScrollToTop;

样式组件

 import styled from 'styled-components'

export const ScrollToTopWrapper = styled.div`
    
    div{
        width: 1rem;
        height: 1rem;
        text-align: center;
        font-size: .6rem;
        color:#666;
        position: fixed;
        right: .3rem;
        bottom: 1.5rem;
        // left: 7rem;
        background-color: #fff;
        border-radius: 50%;
        border-sizing: border-box;
        font-weight: normal;
        span{
            margin-top: .2rem;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值