如何使用React Bootstrap分页动态添加活动类?

huangapple go评论71阅读模式
英文:

How to add active class dynamically using react bootstrap pagination.?

问题

I have an items api which is working fine and I added the active className on Pagination.Item but its not working. I'm not sure if I missed something else to make it work.

See docs for pagination react-bootstrap.github.io

Below is my code and also here is the sandbox code https://codesandbox.io/.

Movielist.js

import { React, useState, useEffect } from "react";
import { Col, Card, Row, Pagination } from "react-bootstrap";
import MovieListPagination from "./MovieListPagination";

const MovieList = () => {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  // Default current pages and posts
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(4);
  // Get current posts
  const indexOfLastPost = currentPage * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;
  const currentPosts = items.slice(indexOfFirstPost, indexOfLastPost);
  // Change page
  const paginate = (pageNumber) => setCurrentPage(pageNumber);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          //console.log(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div className="p-3">Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div className="p-3">Loading...</div>;
  } else {
    return (
      <>
        <Row className="justify-content-center">
          {currentPosts.map((item) => (
            <Col sm={6} lg={4} xl={3} className="py-3" key={item.id}>
              <Card bg="dark" text="light" className="text-center h-100">
                <Card.Body>
                  <Card.Title>{item.title}</Card.Title>
                  <Card.Text>{item.body}</Card.Text>
                </Card.Body>
              </Card>
            </Col>
          ))}
          <Pagination className="justify-content-center">
            <MovieListPagination
              postsPerPage={postsPerPage}
              totalPosts={items.length}
              paginate={paginate}
            />
          </Pagination>
        </Row>
      </>
    );
  }
};

export default MovieList;

MovielistPagination.js

import { React } from "react";
import { Pagination } from "react-bootstrap";

const MovieListPagination = ({
  currentPage,
  postsPerPage,
  totalPosts,
  paginate
}) => {
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }
  return (
    <>
      <Pagination.First />
      <Pagination.Prev />
      {pageNumbers.map((number) => (
        <Pagination.Item
          key={number}
          className={`${currentPage === number ? "active" : ""}`}
          onClick={() => {
            paginate(number);
          }}
        >
          {number}
        </Pagination.Item>
      ))}
      <Pagination.Next />
      <Pagination.Last />
    </>
  );
};

export default MovieListPagination;
英文:

I have an items api which is working fine and I added the active className on Pagination.Item but its not working. I'm not sure if I missed something else to make it work.

See docs for pagination react-bootstrap.github.io

Below is my code and also here is the sandbox code https://codesandbox.io/.

Movielist.js

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { React, useState, useEffect } from &quot;react&quot;;
import { Col, Card, Row, Pagination } from &quot;react-bootstrap&quot;;
import MovieListPagination from &quot;./MovieListPagination&quot;;
const MovieList = () =&gt; {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Default current pages and posts
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(4);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = items.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = (pageNumber) =&gt; setCurrentPage(pageNumber);
useEffect(() =&gt; {
fetch(&quot;https://jsonplaceholder.typicode.com/posts&quot;)
.then((res) =&gt; res.json())
.then(
(result) =&gt; {
setIsLoaded(true);
setItems(result);
//console.log(result.results);
},
(error) =&gt; {
setIsLoaded(true);
setError(error);
}
);
}, []);
if (error) {
return &lt;div className=&quot;p-3&quot;&gt;Error: {error.message}&lt;/div&gt;;
} else if (!isLoaded) {
return &lt;div className=&quot;p-3&quot;&gt;Loading...&lt;/div&gt;;
} else {
return (
&lt;&gt;
&lt;Row className=&quot;justify-content-center&quot;&gt;
{currentPosts.map((item) =&gt; (
&lt;Col sm={6} lg={4} xl={3} className=&quot;py-3&quot; key={item.id}&gt;
&lt;Card bg=&quot;dark&quot; text=&quot;light&quot; className=&quot;text-center h-100&quot;&gt;
&lt;Card.Body&gt;
&lt;Card.Title&gt;{item.title}&lt;/Card.Title&gt;
&lt;Card.Text&gt;{item.body}&lt;/Card.Text&gt;
&lt;/Card.Body&gt;
&lt;/Card&gt;
&lt;/Col&gt;
))}
&lt;Pagination className=&quot;justify-content-center&quot;&gt;
&lt;MovieListPagination
postsPerPage={postsPerPage}
totalPosts={items.length}
paginate={paginate}
/&gt;
&lt;/Pagination&gt;
&lt;/Row&gt;
&lt;/&gt;
);
}
};
export default MovieList;

<!-- end snippet -->

MovielistPagination.js

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { React } from &quot;react&quot;;
import { Pagination } from &quot;react-bootstrap&quot;;
const MovieListPagination = ({
currentPage,
postsPerPage,
totalPosts,
paginate
}) =&gt; {
const pageNumbers = [];
for (let i = 1; i &lt;= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
&lt;&gt;
&lt;Pagination.First /&gt;
&lt;Pagination.Prev /&gt;
{pageNumbers.map((number) =&gt; (
&lt;Pagination.Item
key={number}
className={`${currentPage === number ? &quot;active&quot; : &quot;&quot;}`}
onClick={() =&gt; {
paginate(number);
}}
&gt;
{number}
&lt;/Pagination.Item&gt;
))}
&lt;Pagination.Next /&gt;
&lt;Pagination.Last /&gt;
{/* {item.alt_description ? item.alt_description : item.user.name + &#39; Collection&#39;} */}
&lt;/&gt;
);
};
export default MovieListPagination;

<!-- end snippet -->

答案1

得分: 1

currentPage 传递给组件

<MovieListPagination
  currentPage={currentPage}     // 你遗漏了这一行
  postsPerPage={postsPerPage}
  totalPosts={items.length}
  paginate={paginate}
/>
英文:

Pass currentPage to the Component

&lt;MovieListPagination
currentPage={currentPage}     // You missed this line
postsPerPage={postsPerPage}
totalPosts={items.length}
paginate={paginate}
/&gt;

答案2

得分: 0

在这个组件中,您获取了 "currentPage" 属性,但在使用组件时未传递该属性。在使用组件时,您必须像这样传递属性:

<MovieListPagination
    currentPage={currentPage}
    postsPerPage={postsPerPage}
    totalPosts={items.length}
    paginate={paginate}
/>

另外,即使传递了这个属性,也不会看到类,因为您使用了错误的验证方式。我假设您想要使用类型检查。如果要进行类型检查,您必须进行类型检查:

className={`${typeof currentPage === "number" ? "active" : ""}`}
英文:

In this component, you take the "currentPage" prop, but don't pass that prop when using the component. At the time of using the component, you must pass props like this:

`&lt;MovieListPagination
currentPage={currentPage}     &lt;&lt;
postsPerPage={postsPerPage}
totalPosts={items.length}
paginate={paginate} 
/&gt;`

Also, even if you pass this prop, you won't see the class because you're using validation incorrectly. I'm assuming you want to use type checking. If you want to use type checking, you must typecheck
>className={``${typeof currentPage === "number" ? "active" : ""}`}

答案3

得分: 0

你忘记将 currentPage 属性传递给 MovieListPagination 组件。

<MovieListPagination
  currentPage={currentPage}     // 添加这一行
  postsPerPage={postsPerPage}
  totalPosts={items.length}
  paginate={paginate}
/>
英文:

you forgot to pass currentPage prop to MovieListPagination component

    &lt;MovieListPagination
currentPage={currentPage}     // add this line
postsPerPage={postsPerPage}
totalPosts={items.length}
paginate={paginate}
/&gt;

huangapple
  • 本文由 发表于 2023年2月27日 17:35:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定