簡體   English   中英

使用無限滾動進行滾動高度調整

[英]Scroll height adjustment with infinity scroll

在“滾動”位於最底部的那一刻,調用函數getUsers () 如何設置滾動使其不會到達滑塊的末尾,並調用getUsers ()函數。 會有無限滾動效果。 我的意思是像這里的滾動效果: https : //codesandbox.io/s/ww7npwxokk 當滾動到達底部時,它返回。

代碼在這里: https : //stackblitz.com/edit/react-nq8btq

import './style.css';
import axios from 'axios';

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: [],
      page: 1
    };
  }

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => { 
      this.setState({
        users: res.data
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  scroll = (e) => {
    const page = this.state.page;
    const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
    if (bottom) { 
      alert('bottom');
      this.getUsers()

      this.setState({
        page: this.state.page + 1
      })
    }

    const top = e.target.scrollTop; 

     if(top === 0 && page > 1) {
        alert('I AM AT THE TOP');

         this.setState({
          page: this.state.page - 1
        })
      }
  }

  render() {
    console.log(this.state.page)
     console.log(this.state.users)
    return (
      <div>
         <div onScroll={this.scroll} className="container">
            <ul>
              {this.state.users.map((user, index) => 
                <li>
                  {user.name}
                </li>   
              )}
            </ul>
         </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

在這里,我更新了您的代碼,稍微簡化了一些,但主要是您的代碼注釋了關鍵點。

class App extends Component {
  state = {
    users: [],
    page: 1
  };

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => { 
      this.setState({
        // *you must append to users in state, otherwise 
        // the list will not grow as the user scrolls
        users: [...this.state.users, ...res.data],
        page: this.state.page + 1
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  scroll = (e) => {
    // *simplified, to only handle appending to the list
    // note the 50px from the bottom, adjust as required
    // so that the request is made before the users reaches
    // the bottom of the page under normal scrolling conditions.  
    if (e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight + 50) { 
      this.getUsers();
    }
  }

  render() {
    return (
      <div onScroll={this.scroll} className="container">
        <ul>
          {this.state.users.map((user, index) =>
            // *always add a unique key for each item
            <li key={user.name}>
              {user.name}
            </li>   
          )}
        </ul>
      </div>
    );
  }
}

您需要做的就是決定何時調用 get 用戶。

即,如果您希望在已經滾動到高度的 70% 時調用它,那么該系數將為 0.3 (30%)

每當滾動超過 70% 標記時,就會調用this.getusers()

看看我是如何修改你寫的相同條件的。

其余代碼保持不變

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import axios from 'axios';

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: [],
      page: 1
    };
  }

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => { 
      this.setState({
        users: res.data
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  scroll = (e) => {
    const page = this.state.page;
    const bottom = e.target.scrollHeight - e.target.scrollTop < e.target.clientHeight-0.3*e.target.clientHeight;
    if (bottom) { 
      alert('bottom');
      this.getUsers()

      this.setState({
        page: this.state.page + 1
      })
    }

    const top = e.target.scrollTop; 

     if(top === 0 && page > 1) {
        alert('I AM AT THE TOP');

         this.setState({
          page: this.state.page - 1
        })
      }
  }

  render() {
    console.log(this.state.page)
     console.log(this.state.users)
    return (
      <div>
         <div onScroll={this.scroll} className="container">
            <ul>
              {this.state.users.map((user, index) => 
                <li>
                  {user.name}
                </li>   
              )}
            </ul>
         </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

這個應該為你做的伎倆

$ yarn add react-infinite-scroller

實施起來非常簡單

<InfiniteScroll
  pageStart={0}
  loadMore={this.getUsers()}
  hasMore={this.state.hasMoreUsers}
  loader={<div key={0}>loading ...</div>}
> 
  <li>
    {user.name}
  </li>
</InfiniteScroll>

不要忘記在組件文件中導入 lib

import InfiniteScroll from 'react-infinite-scroller';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM