4 回答
TA贡献1853条经验 获得超9个赞
您可以添加onItemClick方法,并通过使用柯里化可以捕获该值:
const onItemClick = page => event => {
event.preventDefault();
console.log({ page })
setCount(page)
}
然后添加onClick每个项目
for (let number = 1; number <= 10; number++) {
items.push(
<Pagination.Item key={number} active={number === count + 1} onClick={onItemClick(number)}>
{number}
</Pagination.Item>
);
}
const { Pagination } = ReactBootstrap;
function App() {
const [count, setCount] = React.useState(0);
function incrementCount() {
setCount(prevCount => prevCount + 1)
}
function decrementCount() {
setCount(prevCount => prevCount - 1)
}
const onItemClick = page => event => {
event.preventDefault();
console.log({ page })
setCount(page)
}
let items = [];
for (let number = 1; number <= 10; number++) {
items.push(
<Pagination.Item key={number} active={number === count + 1} onClick={onItemClick(number)}>
{number}
</Pagination.Item>
);
}
const paginationBasic = (
<div>
<Pagination>
<Pagination.Prev onClick={decrementCount} />
<Pagination>{items}</Pagination>
<Pagination.Next onClick={incrementCount} />
</Pagination>
</div>
);
return (
<div>
<p>Count {count}</p>
{paginationBasic}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous"
/>
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@16.8/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16.8/umd/react-dom.production.min.js"></script>
<script
src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"
crossorigin></script>
TA贡献1848条经验 获得超10个赞
我想这就是你想要实现的目标
<Pagination.Item key={number}
active={number === count + 1}
onClick={setCount.bind(null, number)}>
{number}
</Pagination.Item>,
TA贡献1817条经验 获得超14个赞
试试这个方法
const pageChanged = (e) => {
setCount(Number(e.target.text )- 1);
}
<Pagination onClick={pageChanged}>
.......
</Pagination>
TA贡献1860条经验 获得超9个赞
您可以将onClick处理程序附加到Pagination.Item组件并将当前索引包含在回调中。我建议对页面项目进行零索引,这样您就不需要设置/比较 +/- 1。
function App() {
const [count, setCount] = useState(0);
function incrementCount() {
setCount((prevCount) => prevCount + 1);
}
function decrementCount() {
setCount((prevCount) => prevCount - 1);
}
let items = [];
for (let number = 0; number < 10; number++) { // <-- 0-index
items.push(
<Pagination.Item
key={number}
onClick={() => setCount(number)} // <-- enclose current number/index value
active={number === count} // <-- compare to current count value
>
{number + 1} // <-- transform data to displayable value
</Pagination.Item>
);
}
const paginationBasic = (
<div>
<Pagination>
<Pagination.Prev onClick={decrementCount} />
{items}
<Pagination.Next onClick={incrementCount} />
</Pagination>
</div>
);
return (
<div>
<p>Hello Stack</p>
{paginationBasic}
</div>
);
}
添加回答
举报