react上拉加载(元素,滚动条在元素上)
js
class TrianCourse extends Component {
constructor(props) {
super(props);
this.state = {
courseData: null,
getDataConfig: {
pIndex: 1,
pSize: 6,
courseType: 3,
trainType: -1,
isPay: false,
isAlbum:true
}
}
}
componentDidMount() {
this.getData();
//给元素添加滚动监听
document.getElementById("train-course").addEventListener('scroll', () => this.watchOnscroll());
}
watchOnscroll() {
let scrollTop = document.getElementById("train-course").scrollTop;//滚动条卷去的高度
let clientHeight = document.getElementById("train-course").clientHeight;//可视区域高度
let scrollHeight = document.getElementById("train-course").scrollHeight;//元素总高度
console.log(scrollTop, clientHeight, scrollHeight)
if (scrollTop + clientHeight+1 >= scrollHeight) {//andriod少1px
if (this.state.getDataConfig.pIndex >= this.state.courseData.Pages) {
Toast.fail("没有更多数据")
return
}
this.setState({
getDataConfig: Object.assign({}, this.state.getDataConfig, {
pIndex: this.state.getDataConfig.pIndex + 1
})
}, () => this.getData())
}
}
//获取列表接口
getData = () => {
Toast.loading("loading...")
//这里是自己调取接口的方法
Base.GetAllCoursePage(this.state.getDataConfig).then(res => {
if (res.Ret === 0) {
Toast.hide()
console.log(res.Data)
if (this.state.getDataConfig.pIndex === 1) {
this.setState({
courseData: res.Data
})
}else{
let arr =this.state.courseData.ViewModelList.concat(res.Data.ViewModelList)
this.setState({
courseData:Object.assign({},this.state.courseData,{
ViewModelList:arr
})
})
}
} else {
console.log(res.Msg)
}
})
}
render() {
const {courseData} = this.state
return (
<div className='train-course' id='train-course'>
{
courseData && courseData.ViewModelList.length !== 0 && courseData.ViewModelList.map((item, key) => {
//ViewModelList是请求回来的数据,是一个数组
return (
<div className='list' key={item.ID}>
<div className="left-logo">
<img src={item.CoverImg} alt=""/>
</div>
<div className='right-content'>
<p>{item.Name}</p>
<p>这是一位可爱的宝宝</p>
<p>时间:<span>2017年7月五号</span></p>
</div>
</div>
)
})
}
{/*<div className='load'>可在此处设置其他加载中样式</div>*/}
</div>
)
}
}
export default TrianCourse;
css
.load{
font-size: 0.3rem;
text-align: center;
}
.train-course{
height: 100vh;//必须小于所有列表总高度之和(如:一个列表的高度是20px,则10个列表就是200px,那么滚动元素盒子的高度就必须小于200px)
overflow: auto;
.list{
display: flex;
font-size: 0.3rem;
align-items: center;
.left-logo{
width:1.5rem;
height: 1.5rem;
padding: 0.3rem;
img{
width: 100%;
height: 100%;
}
}
}
}
下次将列表页进入详情页之后,返回时,记录进入时的位置~~~