【问题标题】:How to scroll to top at each page change on Pagination component?如何在分页组件的每个页面更改时滚动到顶部?
【发布时间】:2022-07-08 09:49:10
【问题描述】:

由于我的分页组件,我希望在更改页面时自动向上滚动。它工作得很好,但我想添加这个功能。我不知道该怎么做..我尝试了一个使用窗口的教程,但它不起作用,因为我没有重定向,只是一个分为几个页面的组件(事件列表)...... 谢谢!!这是我的代码:

分页组件

import PropTypes from 'prop-types';
// import { LinkContainer } from 'react-router-bootstrap';
import './pagination.scss';

const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
  const pageNumbers = [];
  // eslint-disable-next-line no-plusplus
  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }
  return (
    <nav expand="lg" id="pagination-navbar">
      <ul className="pagination">
        {pageNumbers.map((number) => (
          <li key={number} className="page-item">
            <a
              style={{ cursor: 'pointer' }}
              onClick={() => paginate(number)}
              className="page-link"
            >{number}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
};
Pagination.propTypes = {
  postsPerPage: PropTypes.number.isRequired,
  totalPosts: PropTypes.number.isRequired,
  paginate: PropTypes.func.isRequired,

};
export default Pagination;

使用分页的文件

import { useState } from 'react';
import { useSelector } from 'react-redux';
// import react-Bootstrap's component(s)
import {
  Row,
} from 'react-bootstrap';
// import { useLocation } from 'react-router-dom';
import SearchBar from 'src/components/SearchBar';
import Pagination from 'src/components/Pagination';
import EventCard from '../EventCard';

import './eventsList.scss';

const EventsList = () => {
  // TODO code to retrieve the id with a useLocation (not found yet)
  // we use useLocation to retrieve the state of the route
  // in which we have stored genreId or regionId
  // if location is defined, take me its state
  // if the state is defined take me the region
  // console.log(location.state); => returns null
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(9);

  const { eventsList } = useSelector((state) => state.events);
  // Get current posts
  const indexOfLastPost = currentPage * postsPerPage;
  const indexofFirstPost = indexOfLastPost - postsPerPage;
  const currentEvents = eventsList.slice(indexofFirstPost, indexOfLastPost);
  // Change page
  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  return (
    <div>
      <SearchBar
      // we pass a string to change the title according to the page
      // we pass the length of the table to boost the results in the title
        results={eventsList.length}
        message="results"
        // genreId={genreId}
        // regionId={regionId}
      />
      <Row>
        {currentEvents.map((item) => (
          <EventCard key={item.id} {...item} />
        ))}
      </Row>
      <Pagination
        postsPerPage={postsPerPage}
        totalPosts={eventsList.length}
        paginate={paginate}

      />
    </div>
  );
};
export default EventsList;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以使用 React Refs:https://reactjs.org/docs/refs-and-the-dom.html

    您创建一个 ref,将其附加到要滚动到的元素上,并在页面更改时滚动到该元素。

    类似:

    const EventsList = () => {
      const pageTopRef = useRef(null);
      
      const paginate = (pageNumber) => {
        setCurrentPage(pageNumber);
        pageTopRef.current.scrollIntoView();
      };
    
      return (
        <div>
          ...
          <Row ref={pageTopRef}>
            {currentEvents.map((item) => (
              <EventCard key={item.id} {...item} />
            ))}
          </Row>
          ...
        </div>
      );
    };
    

    【讨论】:

    • 非常感谢这个方法效果很好。但在这种情况下,我不明白 useRef() 是干什么用的?我从来没有用过它。你能给我解释一下吗?
    • 我只使用过一次,但我认为这是与 DOM 交互的 React 方式。您可以使用它,而不是使用通过 id 获取元素的 Javascript。它保存对 HTML 元素的引用,然后您可以使用该引用来调用方法,例如 scrollIntoView。
    • 另外,如果解决了,你能接受答案吗?
    • 当然!对不起,我忘记了。谢谢你的解释!
    【解决方案2】:

    这似乎对我有用。 MUI v5,反应

    ...

    const [page, setPage] = useState(props.props.pagination.page);
    

    ...

      useEffect(() => {
        window.scrollTo({
          top: 0,
          left: 0,
          behavior: 'smooth',
        });
      }, [page]);
    

    ...

      const handleChange = (event, value) => {
        setIsLoading(true);
        setPage(value);
      };
    

    ...

        <Pagination
          ...
          count={pageCount}
          page={page}
          onChange={handleChange} 
          ...       
        />
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2019-08-04
      • 2021-02-13
      • 2022-12-31
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多