今天我們將了解如何從頭開始創(chuàng)建分頁并使其可訪問和可重用。希望對您有幫助,歡迎在文末留言評論!
Github:https://github.com/micaavigliano/accessible-pagination
項目:https://accessible-pagination.vercel.app/
自定義鉤子來獲取數(shù)據(jù)
const useFetch = <T,>(url: string, currentPage: number = 0, pageSize: number = 20) => { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<boolean>(false); useEffect(() => { const fetchData = async() => { setLoading(true); setError(false); try { const response = await fetch(url); if (!response.ok) { throw new Error('network response failed') } const result: T = await response.json() as T; setData(result) } catch (error) { setError(true) } finally { setLoading(false); } }; fetchData() }, [url, currentPage, pageSize]); return { data, loading, error, } };
- 我們將生成一個具有通用類型的自定義鉤子。這將允許我們指定使用此鉤子時期望的數(shù)據(jù)類型
- 讓我們等待3個參數(shù)。一個用于 url,我們將在其中獲取數(shù)據(jù),currentPage 是我們所在的頁面,默認情況下它是 0,pageSize 是數(shù)字我們每頁將包含的項目數(shù),默認情況下為 20(您可以更改此值)。
- 在我們的狀態(tài) const [data, setData] = useState
(空);我們將其傳遞給通用類型 T,因為當我們將它用于不同的數(shù)據(jù)請求時,我們將期望不同類型的數(shù)據(jù)。
分頁
為了使頁面可訪問,我們必須考慮以下幾點:
- 焦點必須穿過頁面的所有交互元素,并有一個可見的指示器
- 為了確保與屏幕閱讀器的良好交互,我們必須正確使用區(qū)域、屬性和狀態(tài)
- 頁面必須分組在標簽內(nèi),并包含將其標識為頁面本身的 aria-label。
- 分頁中的每個項目都必須包含 aria-setsize 和 aria-pointset?,F(xiàn)在,它們是做什么用的? aria-setsize 用于計算分頁列表中的項目總數(shù)。屏幕閱讀器將按如下方式宣布:
aria-pointset 用于計算該項目在頁面上所有項目中的位置。屏幕閱讀器將按如下方式宣布:
- 每個項目都必須有一個 aria-label,以便能夠識別單擊該按鈕時我們將轉(zhuǎn)到哪個頁面。
- 有按鈕可以轉(zhuǎn)到下一個/上一個元素,并且每個按鈕都必須有其相應(yīng)的 aria-label
- 如果我們的分頁包含省略號,則必須使用 aria-label 正確標記它
- 每次我們進入新頁面時,屏幕閱讀器都必須宣布我們所在的頁面以及有多少個新項目,如下所示。
為了實現(xiàn)這一點,我們將對其進行如下編碼:
const useFetch = <T,>(url: string, currentPage: number = 0, pageSize: number = 20) => { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<boolean>(false); useEffect(() => { const fetchData = async() => { setLoading(true); setError(false); try { const response = await fetch(url); if (!response.ok) { throw new Error('network response failed') } const result: T = await response.json() as T; setData(result) } catch (error) { setError(true) } finally { setLoading(false); } }; fetchData() }, [url, currentPage, pageSize]); return { data, loading, error, } };
當頁面停止加載時,我們將使用 currentPage 和我們正在加載的新數(shù)組的長度設(shè)置一條新消息。
現(xiàn)在是的!讓我們看看文件 pagination.tsx
中的代碼結(jié)構(gòu)如何該組件需要五個道具
const [statusMessage, setStatusMessage] = useState<string>(""); useEffect(() => { window.scrollTo({ top: 0, behavior: 'smooth' }); if (!loading) { setStatusMessage(`Page ${currentPage} loaded. Displaying ${data?.near_earth_objects.length || 0} items.`); } }, [currentPage, loading]);
-
currentPage 將引用當前頁面。我們將通過在要使用分頁的組件中來處理此問題,如下所示: const [currentPage, setCurrentPage] = useState
(1); - totalPages 是指 API 包含的要顯示的項目總數(shù)。
- nextPage 此函數(shù)將允許我們轉(zhuǎn)到下一頁并更新 currentPage 狀態(tài),如下所示:
interface PaginationProps { currentPage: number; totalPages: number; nextPage: () => void; prevPage: () => void; goToPage: (page: number) => void; }
- prevPage 此函數(shù)將允許我們轉(zhuǎn)到當前頁面的上一頁并更新 currentPage 狀態(tài)
const handlePageChange = (newPage: number) => { setCurrentPage(newPage); }; const nextPage = () => { if (currentPage < totalPages) { handlePageChange(currentPage + 1); } };
- goToPage 這個函數(shù)需要一個數(shù)字參數(shù),它是每個項目必須能夠轉(zhuǎn)到所需頁面的函數(shù)。讓我們按如下方式使其工作:
const prevPage = () => { if (currentPage > 1) { handlePageChange(currentPage - 1); } };
為了使我們的分頁變得生動,我們還需要一步,創(chuàng)建我們將在列表中迭代的數(shù)組!為此,我們必須遵循以下步驟:
- 創(chuàng)建一個函數(shù),在本例中我將其命名為 getPageNumbers
- 為列表中的第一個和最后一個項目創(chuàng)建變量。
- 為左側(cè)的省略號創(chuàng)建一個變量。根據(jù)我自己的決定,我的省略號將位于列表的第四個元素之后。
- 為右側(cè)的省略號創(chuàng)建一個變量。根據(jù)我自己的決定,我的省略號將放在列表中的三個項目之前。
- 創(chuàng)建一個函數(shù),返回一個數(shù)組,其中 5 個項目始終居中,即當前頁面、前兩個項目和后兩個項目。如果需要,我們將排除第一頁和最后一頁
const pagesAroundCurrent = [currentPage - 2, currentPage - 1, currentPage, currentPage 1, currentPage 2].filter(page => page >firstPage && page
- 對于最后一個變量,我們將創(chuàng)建一個包含所有先前創(chuàng)建的變量的數(shù)組。
- 最后,我們將過濾掉空元素并返回數(shù)組。
我們將通過該數(shù)組來獲取頁面中的項目列表,如下所示:
const useFetch = <T,>(url: string, currentPage: number = 0, pageSize: number = 20) => { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<boolean>(false); useEffect(() => { const fetchData = async() => { setLoading(true); setError(false); try { const response = await fetch(url); if (!response.ok) { throw new Error('network response failed') } const result: T = await response.json() as T; setData(result) } catch (error) { setError(true) } finally { setLoading(false); } }; fetchData() }, [url, currentPage, pageSize]); return { data, loading, error, } };
以下是如何制作可重用且易于訪問的分頁!就我個人而言,我學習了如何從頭開始創(chuàng)建頁面,因為我必須在實時編碼中實現(xiàn)它,我希望我的經(jīng)驗對您的職業(yè)生涯有所幫助,并且您可以實現(xiàn)甚至改進它!
您好,
云母
以上是可訪問的組件:分頁的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機

Video Face Swap
使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級代碼編輯軟件(SublimeText3)

javascriptisidealforwebdevelogment,whilejavasuitslarge-scaleapplicationsandandandroiddevelopment.1)javascriptexceleatingingingingingingingbeatingwebexperienceswebexperienceswebexperiencesandfull-stackdeevermentwithnode.js.2)

在JavaScript中,選擇單行注釋(//)還是多行注釋(//)取決于注釋的目的和項目需求:1.使用單行注釋進行快速、內(nèi)聯(lián)的解釋;2.使用多行注釋進行詳細的文檔說明;3.保持注釋風格的一致性;4.避免過度注釋;5.確保注釋與代碼同步更新。選擇合適的注釋風格有助于提高代碼的可讀性和可維護性。

是的,javascriptcommentsarenectary和shouldshouldshouldseffectional.1)他們通過codeLogicAndIntentsgudedepleders,2)asevitalincomplexprojects,和3)handhanceClaritywithOutClutteringClutteringThecode。

Java和JavaScript是不同的編程語言,各自適用于不同的應(yīng)用場景。Java用于大型企業(yè)和移動應(yīng)用開發(fā),而JavaScript主要用于網(wǎng)頁開發(fā)。

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

評論arecrucialinjavascriptformaintainingclarityclarityandfosteringCollaboration.1)heelpindebugging,登機,andOnderStandingCodeeVolution.2)使用林格forquickexexplanations andmentmentsmmentsmmentsmments andmmentsfordeffordEffordEffordEffordEffordEffordEffordEffordEddeScriptions.3)bestcractices.3)bestcracticesincracticesinclud

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)
