index.js文件
import React, { useEffect } from 'react';
import './index.less';
const PullToRefresh = (props) => {
//damping 下拉的最大距离
// onRefresh 为刷新时的回调函数
// refresh 判断当前的刷新状态
//children 为该组件包含的内容
//height 为滚动的区域高度,即超出高度为多少就滚动
let { damping = 60, onRefresh, refresh, children, height } = props;
useEffect(() => {
let list = document.getElementById('list-content-1');
list.style.height = parseInt(height) + 'px';
list.style.overflowY = 'auto';
list.style.overflowX = 'hidden';
}, [height]);
useEffect(() => {
let list = document.getElementById('list-content-1');
let loading = document.getElementById('loading-1');
let startY, endY;
const touchstart = (e) => {
startY = e.touches[0].pageY;
};
const touchmove = (e) => {
endY = e.touches[0].pageY;
let diff = startY - endY; // < 0 说明向下移动
if (diff < 0 && list.scrollTop === 0) {
loading.innerText = Math.abs(diff) > 40 ? '松手立即刷新' : '下拉可以刷新';
list.style.transition = 'all 0.3s';
list.style.marginTop =
Math.abs(diff) > damping ? damping / 2 + 'px' : Math.abs(diff) / 2 + 'px';
}
};
const touchend = () => {
let diff = startY - endY;
if (diff <= -40 && list.scrollTop <= 0) {
// 只有向下才可以刷新
if (Math.abs(diff) < damping) {
list.style.marginTop = Math.abs(diff) / 2 + 'px';
} else {
list.style.marginTop = damping / 2 + 'px';
}
loading.innerText = '正在刷新';
onRefresh();
} else if (0 > diff > -40) {
// 下拉幅度不够,没有触发下拉刷新
list.style.marginTop = 0;
}
};
list.addEventListener('touchstart', touchstart);
list.addEventListener('touchmove', touchmove);
list.addEventListener('touchend', touchend);
return () => {
list.removeEventListener('touchstart', touchstart);
list.removeEventListener('touchmove', touchmove);
list.removeEventListener('touchend', touchend);
};
}, []);
useEffect(() => {
let list = document.getElementById('list-content-1');
let loading = document.getElementById('loading-1');
if (refresh) {
loading.innerText = '刷新完成';
list.style.marginTop = 0;
list.style.transition = 'all 0.3s';
}
}, [refresh]);
return (
<div id="pullToRefresh-1">
<div id="loading-1" />
<div id="list-content-1">{children}</div>
</div>
);
};
export default PullToRefresh;
index.less
#pullToRefresh-1 {
width: 100%;
height: 100%;
background: transparent;
position: relative;
}
#loading-1 {
width: 100%;
height: 24px;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: -40px;
left: 0;
font-size: 1rem;
background: transparent;
color: grey;
padding-top: 16px;
}
#list-content-1 {
width: 100%;
height: auto;
}
quote.jsx 组件引用
import React, {useState} from 'react';
import PullToRefresh from "./index";
const Quote = () => {
// 此处为滚动区域的高度
const [height, setHeight] =useState( document.documentElement.clientHeight);
const onRefresh = () => {
console.log('刷新时的操作')
};
return <PullToRefresh onRefresh={onRefresh} refresh={true /*false*/} height={height}>
<div>此处为滚动的内容</div>
</PullToRefresh>
};
export default Quote;
这是我基于react-hooks写的一个下拉刷新组件,如果有谁在使用的过程中,发现问题,请麻烦指出。
网友评论