当前位置: 代码网 > it编程>编程语言>Javascript > React实现骨架屏的示例代码

React实现骨架屏的示例代码

2024年11月26日 Javascript 我要评论
背景最近有在项目中使用到骨架屏这个东西,由于项目中使用了antd组件库,所以想当然的就使用了它里面的skeleton组件;但是,使用中,在写完业务代码之后,还需要针对性的处理一下骨架屏相关的代码目的减

背景

最近有在项目中使用到骨架屏这个东西,由于项目中使用了antd组件库,所以想当然的就使用了它里面的skeleton组件

但是,使用中,在写完业务代码之后,还需要针对性的处理一下骨架屏相关的代码

目的

减少骨架屏占用开发时间,最好是自动化生成相关页面的骨架屏

技术栈

react @16.8 >=

sass

实现

开发一个相对自动化的骨架屏组件,只需要在使用骨架屏的业务组件中引入该组件,那么就会自动根据当前的dom结构,生成对应的骨架屏结构。

这里博主自己开发了一款组件,暂且是麻麻得,不过目前是符合我所使用的场景,后续再根据业务继续更新迭代,不过也欢迎大家一起来帮忙完善。

示例代码

暂且使用组件的方式如下,当然感兴趣的可以拿到源码,自己在修改成想要的方式

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="点击刷新" onclick={handlefresh}></button>

      <h1>大家也可以尝试自己去更新dom元素,看看生成的骨架屏是否中意</h1>
      <div>
        {isshow && (
          <fragment>
            <p>这是一个段落</p>
            <p>这是一个段落</p>
            <img src="https://zos.alipayobjects.com/rmsportal/jkjgkefvpupvyrjuimnivslzfwpnjuuz.png" />
            <div
              style={{
                margintop: '20px',
                display: 'flex',
                alignitems: 'center',
                justifycontent: 'space-between',
              }}
            >
              <button>显示</button>
              <p>这是一个段落</p>
              <img src="https://zos.alipayobjects.com/rmsportal/jkjgkefvpupvyrjuimnivslzfwpnjuuz.png" />
            </div>
            <div>
              <button>显示</button>
              <p>这是一个段落</p>
              <img src="https://zos.alipayobjects.com/rmsportal/jkjgkefvpupvyrjuimnivslzfwpnjuuz.png" />

              <div>
                <button>显示</button>
                <p>这是一个段落</p>
                <img src="https://zos.alipayobjects.com/rmsportal/jkjgkefvpupvyrjuimnivslzfwpnjuuz.png" />
                <div
                  style={{
                    margintop: '20px',
                    display: 'flex',
                    alignitems: 'center',
                    justifycontent: 'space-between',
                  }}
                >
                  <button>显示</button>
                  <p>这是一个段落</p>
                  <img src="https://zos.alipayobjects.com/rmsportal/jkjgkefvpupvyrjuimnivslzfwpnjuuz.png" />
                </div>
              </div>
            </div>
          </fragment>
        )}
        <autoskeleton
          loading={loading}
          onloadingsuccess={() => {
            setisshow(true);
          }}
          oncomplete={() => {
            setisshow(false);
          }}
        />
      </div>
    </>
  );
};

核心思路

在某一小块独立的组件中,生成对应的骨架屏。 从使用中,可以看到博主在使用的时候,是吧autoskeleton组件与内容通过一个fragment组件隔离开来,共同存在于一个容器(div)中;

将骨架屏中的组件进行抽离,细分颗粒。 从市面上常用骨架屏来看,无非就是文本和图片两种类型,然后再进行一系列的演变,分成不同的骨架屏中的小组件,这里博主只分为了text和image两种类型骨架屏小组件;

比较粗暴的通过html标签的不同,分为了以上两种小组件,分类代码

/** 为text类型的标签类型组合 */
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类型的标签类型组合 */
export const imagetypes = ['img','svg', 'picture', 'video', 'audio']

生成骨架屏,通过遍历容器中的内容节点。不同分类,渲染不同的小组件,这里需要特别处理的是,如果当前组件是div,并且存在children,那么就继续生成小组件。

核心代码

生成骨架屏组件

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;
  /** 加载完成回调 */
  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;
    /** 除了骨架屏内容以外的元素 */
    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;

涉及到样式,这里博主也贴一下代码,骨架屏的样式还是比较复杂的

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%;
      }
  }
}

小组件的代码就比较简单,只是为了后续维护,抽离出来,这里以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>
    )
}

写在最后

以上如果大家认真跟完之后,应该是可以跟博主一样,拥有同样的效果!

不过呢,怕有些小伙伴为了麻烦,博主也很贴心的把我的组件库发布了,可以直接npm仓库去下载

npm i -s gyp-gao-ui

到此这篇关于react实现骨架屏的示例代码的文章就介绍到这了,更多相关react骨架屏内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com