Next.js 设置统一加载页面
Next.js About 1,561 wordsloading.tsx
与page.tsx
同一层目录中新建loading.tsx
组件。
Component
import styles from './Loading.module.css';
export default function Loading() {
return (
// 外层容器:控制 Loading 在页面中的位置(如居中)
<div className={styles.loadingContainer}>
{/* 旋转的圆圈 */}
<div className={styles.loadingSpinner}></div>
{/* 可选:添加加载文本 */}
<p className={styles.loadingText}>加载中...</p>
</div>
);
}
CSS
/* 外层容器:让 Loading 垂直+水平居中(可根据需求调整) */
.loadingContainer {
user-select: none;
flex:1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 旋转圆圈核心样式 */
.loadingSpinner {
/* 圆圈大小 */
width: 40px;
height: 40px;
/* 用 border 实现圆环:透明边框+单侧有色边框 */
border: 4px solid #f3f3f3; /* 浅色边框(背景色) */
border-top: 4px solid #4CAF50; /* 深色边框(旋转时的高亮边) */
border-radius: 50%; /* 圆形 */
/* 旋转动画:名称 时长 线性 无限循环 */
animation: spin 1s linear infinite;
}
/* 加载文本样式(可选) */
.loadingText {
margin-top: 16px;
color: #666;
font-size: 14px;
/* 闪烁动画:透明度变化 */
animation: flash 1.5s ease-in-out infinite alternate;
}
/* 定义旋转动画:从 0 度转到 360 度 */
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
/* 定义闪烁动画:透明度从 0.5 到 1 循环 */
@keyframes flash {
from {
opacity: 0.5;
}
to {
opacity: 1;
}
}
Suspense
与React
提供的Suspense
区别:loading.tsx
由Next.js
自动控制,Suspense
可以更细粒度的控制显示与隐藏。
官方文档
https://nextjs.org/docs/app/getting-started/fetching-data#with-loadingjs
Views: 15 · Posted: 2025-10-18
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓

Loading...