React實(shí)現(xiàn)骨架屏的示例代碼
背景
最近有在項(xiàng)目中使用到骨架屏這個(gè)東西,由于項(xiàng)目中使用了antd組件庫,所以想當(dāng)然的就使用了它里面的Skeleton組件;
但是,使用中,在寫完業(yè)務(wù)代碼之后,還需要針對性的處理一下骨架屏相關(guān)的代碼
目的
減少骨架屏占用開發(fā)時(shí)間,最好是自動(dòng)化生成相關(guān)頁面的骨架屏
技術(shù)棧
react @16.8 >=
sass
實(shí)現(xiàn)
開發(fā)一個(gè)相對自動(dòng)化的骨架屏組件,只需要在使用骨架屏的業(yè)務(wù)組件中引入該組件,那么就會自動(dòng)根據(jù)當(dāng)前的dom結(jié)構(gòu),生成對應(yīng)的骨架屏結(jié)構(gòu)。
這里博主自己開發(fā)了一款組件,暫且是麻麻得,不過目前是符合我所使用的場景,后續(xù)再根據(jù)業(yè)務(wù)繼續(xù)更新迭代,不過也歡迎大家一起來幫忙完善。
示例代碼
暫且使用組件的方式如下,當(dāng)然感興趣的可以拿到源碼,自己在修改成想要的方式
import { useState, Fragment, useEffect } from 'react'; import { AutoSkeleton, Button } from 'gyp-gao-ui'; export default () => { const [isShow, setIsShow] = useState(true); const [loading, setLoading] = useState(false); const handleFresh = () => { setLoading(true); setTimeout(() => { setLoading(false); }, 2000); }; /** 模擬請求 */ useEffect(() => { handleFresh(); }, []); return ( <> <Button text="點(diǎn)擊刷新" onClick={handleFresh}></Button> <h1>大家也可以嘗試自己去更新dom元素,看看生成的骨架屏是否中意</h1> <div> {isShow && ( <Fragment> <p>這是一個(gè)段落</p> <p>這是一個(gè)段落</p> <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <button>顯示</button> <p>這是一個(gè)段落</p> <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> </div> <div> <button>顯示</button> <p>這是一個(gè)段落</p> <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> <div> <button>顯示</button> <p>這是一個(gè)段落</p> <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <button>顯示</button> <p>這是一個(gè)段落</p> <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> </div> </div> </div> </Fragment> )} <AutoSkeleton loading={loading} onLoadingSuccess={() => { setIsShow(true); }} onComplete={() => { setIsShow(false); }} /> </div> </> ); };
核心思路
在某一小塊獨(dú)立的組件中,生成對應(yīng)的骨架屏。 從使用中,可以看到博主在使用的時(shí)候,是吧AutoSkeleton組件與內(nèi)容通過一個(gè)Fragment組件隔離開來,共同存在于一個(gè)容器(div)中;
將骨架屏中的組件進(jìn)行抽離,細(xì)分顆粒。 從市面上常用骨架屏來看,無非就是文本和圖片兩種類型,然后再進(jìn)行一系列的演變,分成不同的骨架屏中的小組件,這里博主只分為了Text和Image兩種類型骨架屏小組件;
比較粗暴的通過html標(biāo)簽的不同,分為了以上兩種小組件,分類代碼
/** 為text類型的標(biāo)簽類型組合 */ export const textTypes = ['p', 'span', 'a', 'button', 'input', 'textarea', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'li', 'ul', 'ol', 'pre', 'code', 'blockquote', 'cite','strong', 'em','mark', 'del', 'ins','sub','sup','small', 'big'] ???????/** 為image類型的標(biāo)簽類型組合 */ export const imageTypes = ['img','svg', 'picture', 'video', 'audio']
生成骨架屏,通過遍歷容器中的內(nèi)容節(jié)點(diǎn)。不同分類,渲染不同的小組件,這里需要特別處理的是,如果當(dāng)前組件是div,并且存在children,那么就繼續(xù)生成小組件。
核心代碼
生成骨架屏組件
import React, { useEffect, useRef, useState } from 'react'; import { comp_className } from '../constants'; import './index.scss'; import { Image, Text, imageTypes, textTypes } from './skeleton'; import { nanoid } from 'nanoid'; export interface IAutoSkeletonProps { /** 生成骨架屏完成 */ onComplete?: () => void; /** * 加載中 * @default true */ loading: boolean; /** 加載完成回調(diào) */ onLoadingSuccess?: () => void; } function AutoSkeleton(props: IAutoSkeletonProps) { const { onComplete, loading = true, onLoadingSuccess } = props; const [showMenu, setShowMenu] = useState(false); const [currentPoint, setCurrentPoint] = useState<{ x: number; y: number }>({ x: 0, y: 0, }); const currentRef = useRef<HTMLDivElement>(null); const [skeleton, setSkeleton] = useState<any>(); const genSkeleton = () => { if (!currentRef.current) return; const parent = currentRef.current.parentElement; if (!parent) return; /** 除了骨架屏內(nèi)容以外的元素 */ const targetElements = Array.from(parent.children).filter( (o) => !o.className.includes(comp_className + 'auto-skeleton'), ); const getSkeletonSon = (elements: Element[], parent: Element) => { const child = elements .map((k) => { if (k.children.length > 0 && k.nodeName.toLowerCase() === 'div') { return getSkeletonSon(Array.from(k.children), k); } if (imageTypes.includes(k.nodeName.toLowerCase())) { return <Image key={nanoid()} />; } if (textTypes.includes(k.nodeName.toLowerCase())) { return <Text key={nanoid()} />; } return null; }) .filter((k) => k !== null); const style = getComputedStyle(parent); return ( <div key={nanoid()} style={{ display: 'flex', width: style.width, flexDirection: style.flexDirection && style.display === 'flex' ? (style.flexDirection as any) : 'column', justifyContent: style.justifyContent, alignItems: style.alignItems, gap: style.gap === 'normal' ? '12px' : style.gap, }} > {child} </div> ); }; const getSkeletonChild = (elements: Element[]) => { return elements .map((o) => { if (o.children.length > 0 && o.nodeName.toLowerCase() === 'div') { return getSkeletonSon(Array.from(o.children), o); } if (imageTypes.includes(o.nodeName.toLowerCase())) { return <Image key={nanoid()} />; } if (textTypes.includes(o.nodeName.toLowerCase())) { return <Text key={nanoid()} />; } return null; }) .filter((o) => o !== null); }; const skeletonContent = getSkeletonChild(targetElements); setSkeleton(skeletonContent); setTimeout(() => { onComplete && onComplete(); setShowMenu(false); }, 0); }; useEffect(() => { if (loading) { genSkeleton(); } else { onLoadingSuccess && onLoadingSuccess(); } }, [loading]); return ( loading && ( <div className={`${comp_className}auto-skeleton`} ref={currentRef} > {skeleton} </div> ) ); } export default AutoSkeleton;
涉及到樣式,這里博主也貼一下代碼,骨架屏的樣式還是比較復(fù)雜的
index.scss
.xxx-auto-skeleton { width: 100%; height: 100%; display: flex; flex-direction: column; gap: 12px; &-image { flex: 0 0 auto; // 防止被擠壓 width: 80px; height: 80px; background: linear-gradient( 90deg, rgba(190, 190, 190, 0.2) 25%, rgba(129, 129, 129, 0.24) 37%, rgba(190, 190, 190, 0.2) 63% ); border-radius: 8px; animation: xxx-skeleton-loading 1.4s ease infinite; background-size: 200% 100%; background-position: 100% 50%; background-position-x: 180%; } &-text { width: 100%; height: 32px; border-radius: 4px; background: linear-gradient( 90deg, rgba(190, 190, 190, 0.2) 25%, rgba(129, 129, 129, 0.24) 37%, rgba(190, 190, 190, 0.2) 63% ); animation: xxx-skeleton-loading 1.4s ease-in-out infinite; background-size: 200% 100%; background-position: 100% 50%; background-position-x: 180%; } @keyframes xxx-skeleton-loading { to { background-position-x: -20%; } } }
小組件的代碼就比較簡單,只是為了后續(xù)維護(hù),抽離出來,這里以Text舉例
import React from 'react'; import { comp_className } from '../../constants'; import '../index.scss'; ???????export default function TextSkeleton() { return ( <div className={`${comp_className}auto-skeleton-text`}></div> ) }
寫在最后
以上如果大家認(rèn)真跟完之后,應(yīng)該是可以跟博主一樣,擁有同樣的效果!
不過呢,怕有些小伙伴為了麻煩,博主也很貼心的把我的組件庫發(fā)布了,可以直接npm倉庫去下載
npm i -S gyp-gao-ui
到此這篇關(guān)于React實(shí)現(xiàn)骨架屏的示例代碼的文章就介紹到這了,更多相關(guān)React骨架屏內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react.js 父子組件數(shù)據(jù)綁定實(shí)時(shí)通訊的示例代碼
本篇文章主要介紹了react.js 父子組件數(shù)據(jù)綁定實(shí)時(shí)通訊的示例代碼,2017-09-09React中使用Axios發(fā)起POST請求提交文件方式
這篇文章主要介紹了React中使用Axios發(fā)起POST請求提交文件方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02React實(shí)現(xiàn)單向數(shù)據(jù)流的方法
本文主要介紹了React實(shí)現(xiàn)單向數(shù)據(jù)流的方法2023-04-04React路由鑒權(quán)的實(shí)現(xiàn)方法
這篇文章主要介紹了React路由鑒權(quán)的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09react.js組件實(shí)現(xiàn)拖拽復(fù)制和可排序的示例代碼
這篇文章主要介紹了react.js組件實(shí)現(xiàn)拖拽復(fù)制和可排序的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08解析TypeError:import_react_native.AppState.removeEventListener
這篇文章主要為大家介紹了TypeError:import_react_native.AppState.removeEventListener?is?not?a?function問題解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09