react 元素滚动 触底

2021-05-24  本文已影响0人  魔仙堡杠把子灬

我不记得小时候的梦想了,但绝对不是买一套房子。

我的github: 李大玄
我的私人博客: 李大玄
我的npm开源库: 李大玄
我的简书: 李大玄
我的CSDN: 李大玄
我的掘金: 李大玄
哔哩哔哩: 李大玄

在这里插入图片描述

export default class Scroll extends Component<Props, State>  {
  private scrollRef: any;
  constructor(props: Props) {
    super(props);
    this.state = {
      tableList: [],
      
    } as State;
    this.initPage = this.initPage.bind(this);
    this.onScrollCapture = this.onScrollCapture.bind(this);
  }
  // 将要装载,在render之前调用;
  // componentWillMount() {}
  // (装载完成),在render之后调用 建议请求接口
  componentDidMount() {
    this.initPage();
  }
  initPage() {
    const arr = [];
    for (let i = 0; i < 30; i++) {
      const obj = {
        name: '李大玄',
        age: 26,
        id: i,
        sex: '男'
      };
      arr.push(obj);
    }
    this.setState({
      tableList: arr
    });
  }
 // 这里是滚动事件
  onScrollCapture() {
    const { scrollTop, clientHeight, scrollHeight } = this.scrollRef;
    
    let time: any = null;
    clearTimeout(time);
    time = setTimeout(() => {
      console.log(scrollTop, clientHeight, scrollHeight );
      if(scrollTop + clientHeight >= scrollHeight){
        //请求逻辑
        console.log('触底了');
      }
    }, 1000);
  }
  render() {
    const {tableList} = this.state;
    const boxStyle = {
      background: 'pink',
      // overflow: 'hidden',
    };
    return(
      <div>
      <!--         !!!!!!!!                 事件:onScrollCapture   ref  -->
        <div className="w300 h300 p10 overauto" onScrollCapture={ this.onScrollCapture } ref={(ref: any) => {this.scrollRef = ref}} style={boxStyle}>
          <ul>
            {
              tableList.map((item, index) => {
                return (
                  <li key={index}> { item.id } - { item.name } - { item.age } - { item.sex } </li>
                );
              })
            }
          </ul>
        </div>
      </div>
    );
  }
}
// 
上一篇 下一篇

猜你喜欢

热点阅读