关于React.js中的残疾人问题
我尝试在加载时禁用一个按钮,然后在完成呈现(或者说获取数据)之后,它将启用该按钮。
下面是代码框链接中的示例:https://codesandbox.io/s/data-fetch-example-oc8eh0?file=/src/App.js
例如:每次我单击“第一”、“前一”、“下一步”和“最后”按钮时。当当前加载数据页时,将禁用所有按钮(而不仅仅是被单击的按钮)。
谢谢
如果您不能打开链接,下面是代码:
import React,{ useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(0);
const [postsPerPage, setPostsPerPage] = useState(10);
useEffect(()=>{
getData();
},[])
async function getData(){
setLoading(true);
const response = await fetch('https://stream-restaurant-menu-svc.herokuapp.com/item?category')
let actualData = await response.json();
setPosts(actualData)
setLoading(false);
}
const indexOfLastPost = (currentPage + 1) * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
const pageNumbers = [];
for (let i = 0; i < Math.ceil(posts.length / postsPerPage); i++) {
pageNumbers.push(i);
}
const incrementPageNumber = () => {
if (currentPage < pageNumbers.length - 1) {
setCurrentPage((previousPageNumber) => previousPageNumber + 1);
}
};
const decrementPageNumber = () => {
if (currentPage > 0) {
setCurrentPage((previousPageNumber) => previousPageNumber - 1);
}
};
// if loading...
if(loading){
return <h2>Loading</h2>
}
return (
<div className="App">
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
{currentPosts.map((post) => (
<tr>
<td key={`${post.id}-id`}>{post.id}</td>
<td key={`${post.name}-firstName`}>{post.name}</td>
<td key={`${post.short_name}-lastName`}>{post.short_name}</td>
</tr>
))}
</tbody>
</table>
<div>
<button
id='first'
type='button'
className='first-page-btn'
disabled={loading || currentPage === 0}
onClick={() => {setCurrentPage(0)}}
>
first
</button>
<button
id='previous'
type='button'
className='previous-page-btn'
disabled={loading || currentPage === 0}
onClick={decrementPageNumber}
>
previous
</button>
<button
id='next'
type='button'
className='next-page-btn'
disabled={loading || currentPage === pageNumbers[pageNumbers.length - 1]}
onClick={incrementPageNumber}
>
next
</button>
<button
id='last'
type='button'
className='last-page-btn'
disabled={loading || currentPage === 0}
onClick={() => setCurrentPage(pageNumbers[pageNumbers.length - 1])}
>
last
</button>
</div>
</div>
);
}发布于 2022-07-12 01:59:52
不幸的是,我不能打开你的链接。这是我的想法。我猜主组件中可能有loading状态。如果不是,您可能拥有data状态,这是您想要在每个分页中下载和更新的数据。
我将以loading为例。您的组件可能与此类似。
function Main() {
return(
<div>
<Pagination disabled={loading} {...other props} />
</div>
)然后,将禁用的道具添加到分页。我认为您的分页是button组件,那么它有disabled属性。或者,如果使用引导,则可以将disabled className传递给button或a元素。
https://stackoverflow.com/questions/72946112
复制相似问题