1.封装scroll-view,在components下创建scrolldemo文件(名字自定义)下在创建两个文件,一个.jsx,一个.css,我这里用的scss,这里可以根据自己需求来定
下面是.jsx文件内容
import React, { Component } from "react"
import { ScrollView, View, Slot } from "@tarojs/components"
import { AtActivityIndicator } from 'taro-ui'
import './scrollDmt.scss'
export default class ScrollDmt extends Component {
state = {
}
render() {
const { children, handleRefresh, isRefresh, handleLoadMore, isLoading } = this.props
return (
<ScrollView
className='scroll-content'
scrollY
refresherEnabled
refresherThreshold={40}
refresherDefaultStyle='none' // 不使用默认样式
refresherBackground='#fff'
refresherTriggered={isRefresh}
onRefresherRefresh={handleRefresh}
lowerThreshold={40}
onScrollToLower={handleLoadMore}
>
{/* 自定义加载动画 start*/}
<Slot name='refresher'>
<View className='refresh-loading'>
<AtActivityIndicator content={!isRefresh ? '刷新中...' : '刷新完成'}></AtActivityIndicator>
</View>
</Slot>
{/* 插槽内容 */}
{children}
{
isLoading && <View className='refresh-loading'>
<AtActivityIndicator content='加载中...'></AtActivityIndicator>
</View>
}
</ScrollView>
)
}
}
下面是.scss内容
.scroll-content {
height: 100%;
}
.refresh-loading {
width: 100vw;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
}
到这里scroll-view就封装好了,接下来是在页面中注册引用
在pages文件下创建页面home.jsx
import Taro from '@tarojs/taro'
import React, { Component } from 'react'
import { View, Image, Swiper, SwiperItem } from '@tarojs/components'
import ScrollDmt from '../../components/scrollDmt/scrollDmt'; // 引入组件
export default class Home extends Component {
state = {
isRefresh: false, // 下拉刷新加载动画的开关
list:[],
pageSize: 10, // 每页几条数据, 默认10条
pageNo: 1, // 当前页
totalCount: 0, // 商品总数
}
// 组件内下拉函数
handleRefresh = () => {
// 下拉把isRefresh置为true,pageNo重置为1
this.setState({ isRefresh: true, pageNo: 1 }, () => {
// 在下拉刷新时加载数据
this.loadData(1)
});
}
loadData = (pageNo) =>{
const { pageSize, list } = this.state;
Taro.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
pageNo,
pageSize
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
const newData = res.data.list;
this.setState({
list: pageNo === 1 ? newData : [...list, ...newData],
totalCount: res.data.totalCount,
isLoading: false,
isRefresh: false,
});
}
})
}
// 上拉加载
handleLoadMore = (e) => {
if (this.state.isLoading || this.noMoreProduct()) {
return
} else {
this.setState(prevState => ({ isLoading: true, pageNo: prevState.pageNo + 1 }), () => {
setTimeout(() => {
this.loadData(this.state.pageNo);
}, 1000)
});
}
}
//判断数据是否全部加载完,如果加载完则不进行加载
noMoreProduct() {
return this.state.goods_list.length >= this.state.totalCount && this.state.totalCount > 0
}
render() {
return (
<View className="page">
<ScrollDmt
handleRefresh={() => this.handleRefresh()}
handleLoadMore={() => this.handleLoadMore()}
isRefresh={isRefresh}>
{/* 这里放页面内容 */}
<View className='' >页面内容</View>
</ScrollDmt>
</View>
)
}
}
这是home.scss
.page{
height:100vh; // 这里高度必须设置,不能为100%
}
具体根据项目需求,