对于移动端APP来说,列表页拉动刷新和加载更多是非常普通的功能。
这里我就分享我实现的一些碎片代码。
拉动刷新
-
对于拉动刷新,直接使用
的是ant-design-mobile中的PullToRefresh 拉动
刷新。按照官网的代码复制下来
import { PullToRefresh, Button } from 'antd-mobile'; function genData() { const dataArr = []; for (let i = 0; i < 20; i++) { dataArr.push(i); } return dataArr; } class Demo extends React.Component { constructor(props) { super(props); this.state = { refreshing: false, down: true, height: document.documentElement.clientHeight, data: [], }; } componentDidMount() { const hei = this.state.height - ReactDOM.findDOMNode(this.ptr).offsetTop; setTimeout(() => this.setState({ height: hei, data: genData(), }), 0); } render() { return (<div> <Button style={ { marginBottom: 15 }} onClick={ () => this.setState({ down: !this.state.down })} > direction: { this.state.down ? 'down' : 'up'} </Button> <PullToRefresh damping={ 60} ref={ el => this.ptr = el} style={ { height: this.state.height, overflow: 'auto', }} indicator={ this.state.down ? { } : { deactivate: '上拉可以刷新' }} direction={ this.state.down ? 'down' : 'up'} refreshing={ this.state.refreshing} onRefresh={ () => { this.setState({ refreshing: true }); setTimeout(() => { this.setState({ refreshing: false }); }, 1000); }} > { this.state.data.map(i => ( <div key={ i} style={ { textAlign: 'center', padding: 20 }}> { this.state.down ? 'pull down' : 'pull up'} { i} </div> ))} </PullToRefresh> </div>); } } ReactDOM.render(<Demo />, mountNode);
其实对于我们实现功能来说,可以去除掉用例的不必要代码(用例获取数据的方法),精简下来就是
如果报错
说找不到ReactDOM,
则需要引入
import ReactDOM from 'react-dom';
import { PullToRefresh, Button } from 'antd-mobile'; class Demo extends React.Component { constructor(props) { super(props); this.state = { refreshing: false, down: true, height: document.documentElement.clientHeight, }; } componentDidMount() { const hei = this.state.height - ReactDOM.findDOMNode(this.ptr).offsetTop; setTimeout(() => this.setState({ height: hei, }), 0); } render() { return ( <div> <PullToRefresh damping={ 60} ref={ el => this.ptr = el} style={ { height: this.state.height, overflow: 'auto', }} indicator={ this.state.down ? { } : { deactivate: '上拉可以刷新' }} direction={ this.state.down ? 'down' : 'up'} refreshing={ this.state.refreshing} onRefresh={ () => { this.setState({ refreshing: true }); setTimeout(() => { this.setState({ refreshing: false }, () => { // ---------------------------- 写自己刷新的事件方法 }); }, 1000); }} > // -------------------放自己的页面布局代码 </div> </PullToRefresh> </div>); } } ReactDOM.render(<Demo />, mountNode);
加载更多
自定义一个数组用来存放页面数据,进行加载更多时候,将新旧数据一起存放进去再进行渲染即可。
点击加载更多页数增加,判断当前页数是否小于总页数去判断是否需要显示加载更多…
-
列出一些伪代码:存放数组
this.setState({ initClassDynamicsList: [...initClassDynamicsList, ...classDynamicsList], initCommentContentList: [...commentContentList, ...initCommentContentList] }, () => { if (pageIndex > 1) { (initClassDynamicsList || []).forEach((item) => { item.commentList.forEach((item2) => { commentIdList.push(item2.commentId) }) accountIdList.push(item.teacherAccountId) })
-