模拟antd-mobile下拉刷新(高手勿喷)

186 阅读1分钟

tsx部分

import React, { Component } from 'react'
import './index.css'
import { PullToRefresh, List } from 'antd-mobile'
import { Slider, Toast } from 'antd-mobile'
export default class index extends Component {
  state = {
    start: 0,
    end: 0,
    top: 0,
    animate: 0,
    text: '下拉刷新',
    arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  }
  render() {
    const { start, end, top, animate, text, arr } = this.state
    return (
      <div
        className='app'
        style={{ top, [animate ? 'transition' : '']: '.3s' }}
        onTouchStart={(e) => {
          this.setState({ start: e.changedTouches[0].pageY, animate: 0, end: 0, text: '下拉刷新' })
        }}
        onTouchMove={(e) => {
          if (document.documentElement.scrollTop > 5) return
          let y = (e.changedTouches[0].pageY - start) / 4
          this.setState({ top: y })
          if (y > 60) this.setState({ end: 1, text: '释放立即刷新' })
        }}
        onTouchEnd={(e) => {
          if (!end) return this.setState({ top: 0, animate: 1 })
          this.setState({ top: 50, animate: 1, text: '刷新中' })
          new Promise((resolve, reject) => {
            setTimeout(() => {
              this.setState({
                text: '刷新完成',
              })
              resolve('')
            }, 1000)
          })
            .then((e) => {
              setTimeout(() => {
                this.setState({
                  top: 0,
                })
              }, 500)
            })
            .then((e) => {
              setTimeout(() => {
                this.setState({
                  end: 0,
                  text: '下拉刷新',
                })
              }, 800)
            })
        }}
      >
        <div className='top'>{text}</div>
        {arr.map((e) => (
          <div className='ww'>{e}</div>
        ))}
      </div>
    )
  }
}

css部分

html,
body {
  width: 100%;
  height: 100%;
}
* {
  margin: 0;
  padding: 0;
}
.app {
  position: absolute;
  width: 100%;
  height: 100%;
}
.top {
  position: absolute;
  width: 100%;
  height: 500px;
  top: -500px;
  text-align: center;
  line-height: 950px;
  background-color: #eee;
}
.ww {
  width: 100%;
  height: 100px;
  text-align: center;
  line-height: 100px;
}