如何在 React 中构建骨架布局
在移动和 Web 应用中,使用骨架布局来呈现异步内容正变得越来越流行。Google、Facebook、LinkedIn、Youtube 等众多应用都使用骨架布局来展示内容和布局在加载前可能呈现的样子。在您自己的项目中使用骨架布局不仅能为用户带来良好的样式效果,还能通过减少“累积布局偏移”来提升项目的 SEO 效果。本文将向您展示如何轻松添加一个在异步内容加载后更新的骨架布局。
isLoaded 状态
React 允许我们将状态设置为异步函数完成时的isLoaded: false
状态isLoaded: true
。这将作为显示内容集的基础。我们将根据 isLoaded 状态为内容创建两个 CSS 类:.loading
和。然后,我们将执行一个 if 语句,如果为 ,则.loaded
返回内容的 JSX 。如果 为,则应用程序将返回内容的 JSX ,这将成为我们的骨架布局。.loaded
isLoaded = true
isLoaded = false
.loading
// JSX
class App extends React.Component {
constructor(props){
super(props);
this.state = {
isLoaded: false,
asyncData: []
}
};
render(){
asyncFunction = () => {
// Async function fetches asyncData, and upon fetch updates state from `isLoaded:false` to `isLoaded:true`
}
if(this.state.isLoaded===true){
// If state.isLoaded=true, component will render complete layout and async content
return(
<>
<LayoutContent className="loaded" />
</>
);
}
return(
// While state.isLoaded=false, component will only render skeleton layout
<>
<LayoutContent className="loading" />
</>
);
};
};
CSS
我们需要样式化的 CSS 将包含两个类:.loading
和.loaded
。这为您提供了一些自由度来决定骨架布局的外观,但我选择了StackFindOver 中的动画方法来设置下面 CodePen 示例中的样式。
// Skeleton Layout styles and animation
.loading {
position: relative;
background: #cccccc;
}
.loading:after {
content: "";
display: block;
position: absolute;
top:0;
width: 100%;
height: 100%;
transform: translateX(-100px);
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
animation: loading 0.8s infinite;
}
@keyframes loading {
100% {
transform: translateX(100%);
}
}
// Loaded styling
.loaded {
// Styles
}
关于 CSS 样式,还有一些需要注意的事项:
- 应该定义组件的宽度和高度,以减少内容跳动
- 考虑使用 CSS Flexbox 来定义响应式组件的最大宽度/高度
- 如果组件大小根据内容而变化,请考虑添加“overflow-y:scroll”属性
示例应用程序
您可以随意从这个CodePen 示例中窃取一些代码,但请注意,您可能需要调整一些样式以适合您自己的应用程序。
结论
骨架布局不仅能为您的应用在异步内容加载时提供有趣且实用的加载屏幕,还能提升应用的 SEO 和用户体验。希望这篇博文和示例能为您提供一些关于如何在自己的项目中应用骨架布局的灵感!
你在项目中使用过骨架布局吗?
如果你也用过类似的方法,或者有什么改进建议,欢迎留言!