React移动端下拉刷新

该博客展示了如何在React中实现一个下拉刷新的组件。通过监听touch事件,计算手指滑动距离,并动态改变元素高度来模拟刷新效果。当滑动超过一定阈值时,触发刷新状态并展示相应提示,最后恢复初始状态。整个过程结合了状态管理和DOM操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

index.tsx 文件

import React, { Component, createRef } from 'react'
import './index.less'
interface iProps { }
interface iState { }
export default class index extends Component<iProps, iState> {
  constructor(props: iProps) {
    super(props)
    this.state = {}
  }
  // 定义数据类型
  disy: number = 0
  y: number = 0
  // 获取当前元素
  top = createRef<HTMLDivElement>()
  // 封装当前元素
  Gettop = () => { return this.top.current as HTMLDivElement }
  // 点击事件
  Fnstart = (e: React.TouchEvent) => {
    // 获取当前手指点击的位置
    this.disy = e.targetTouches[0].pageY
    document.ontouchmove = this.Fnmove.bind(this)
    this.Gettop().style.transition = 'none'
  }
  // 触摸事件
  Fnmove = (e: TouchEvent) => {
    // 当前触摸的点减去刚刚点击的坐标
    this.y = e.targetTouches[0].pageY - this.disy
    // 赋值给元素的高度
    this.Gettop().style.height = this.y + 'px'
    document.ontouchend = this.Fnend.bind(this)
  }
  // 手指抬起事件
  Fnend = (e: TouchEvent) => {
    // 如果触摸下拉的值大于80的话
    if (this.y > 80) {
      this.y = 80
      this.Gettop().style.height = this.y + 'px'
      // 更改元素的内容值
      this.Gettop().innerHTML = '正在刷新..'
      setTimeout(() => {
        this.y = 0
        this.Gettop().style.height = this.y + 'px'
        this.Gettop().innerHTML = '刷新成功..'
      }, 500);
    } else {
      this.y = 0
    }
    this.Gettop().style.height = this.y + 'px'
    // 出现个缓动效果
    this.Gettop().style.transition = '.3s all'
  }
  render() {
    return (
      <div className='box'>
        <div className="top" ref={this.top}>下拉刷新</div>
        <div className="con" onTouchStart={this.Fnstart.bind(this)}>
          <div className="item">A</div>
          <div className="item">B</div>
          <div className="item">C</div>
          <div className="item">D</div>
          <div className="item">E</div>
          <div className="item">F</div>
          <div className="item">G</div>
        </div>
      </div>
    )
  }
}

index.less

.box {
  .top {
    text-align: center;
    height: 0;
    overflow: hidden;
    width: 100%;
    background-color: #f5f7fa;
  }
  .con {
    background-color: #fff;
    height: 100vh;
    width: 100vw;
    .item{
        margin: 15px;
        font-size: 30px;
        line-height: 60px;
        border-bottom: 1px solid #f4f4f4;
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红烧四喜丸子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值