Thu*_*eer 1 css fouc reactjs webpack create-react-app
我已经从 create-react-app 构建了 react.js 站点。但是在生产模式下,有 FOUC,因为样式是在 html 渲染后加载的。
有没有办法解决这个问题?我一直在谷歌上搜索答案,但还没有找到合适的答案。
FOUC - 所谓的无样式内容的 Flash可能与解决此问题的许多尝试一样成问题。
让我们考虑以下路由配置(react-router):
...
<PageLayout>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/example' component={Example} />
<Switch>
</PageLayout>
...
Run Code Online (Sandbox Code Playgroud)
wherePageLayout是一个简单的hoc,包含带有page-layout类的div 包装器并返回它的孩子。
现在,让我们专注于基于路由的组件渲染。通常你会使用componentReact作为道具Compoment。但在我们的例子中,我们需要动态获取它,以应用帮助我们避免 FOUC 的功能。所以我们的代码看起来像这样:
import asyncRoute from './asyncRoute'
const Home = asyncRoute(() => import('./Home'))
const Example = asyncRoute(() => import('./Example'))
...
<PageLayout>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/example' component={Example} />
<Switch>
</PageLayout>
...
Run Code Online (Sandbox Code Playgroud)
为了澄清,让我们也展示一下asyncRoute.js模块的样子:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Loader from 'components/Loader'
class AsyncImport extends Component {
static propTypes = {
load: PropTypes.func.isRequired,
children: PropTypes.node.isRequired
}
state = {
component: null
}
toggleFoucClass () {
const root = document.getElementById('react-app')
if (root.hasClass('fouc')) {
root.removeClass('fouc')
} else {
root.addClass('fouc')
}
}
componentWillMount () {
this.toggleFoucClass()
}
componentDidMount () {
this.props.load()
.then((component) => {
setTimeout(() => this.toggleFoucClass(), 0)
this.setState(() => ({
component: component.default
}))
})
}
render () {
return this.props.children(this.state.component)
}
}
const asyncRoute = (importFunc) =>
(props) => (
<AsyncImport load={importFunc}>
{(Component) => {
return Component === null
? <Loader loading />
: <Component {...props} />
}}
</AsyncImport>
)
export default asyncRoute
Run Code Online (Sandbox Code Playgroud)
hasClass,addClass,removeClass是对 DOM 类属性进行操作的 polyfill。
Loader是一个显示微调器的自定义组件。
为什么setTimeout?
只是因为我们需要fouc在第二个刻度中删除类。否则它会在渲染组件时发生。所以它不会工作。
正如您在AsyncImport组件中看到的,我们通过添加fouc类来修改 React 根容器。为清楚起见,HTML:
<html lang="en">
<head></head>
<body>
<div id="react-app"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和另一块拼图:
#react-app.fouc
.page-layout *
visibility: hidden
Run Code Online (Sandbox Code Playgroud)
sass 在导入特定组件(即:Home, Example)时应用。
为什么不display: none呢?
因为我们希望所有依赖于父宽度、高度或任何其他 css 规则的组件都能正确呈现。
主要假设是隐藏所有元素,直到组件准备好向我们展示渲染的内容。首先它会触发asyncRoute向我们展示Loader直到Component安装和渲染的函数。同时,AsyncImport我们通过fouc在 react 根 DOM 元素上使用类来切换内容的可见性。当一切加载完毕,就该显示所有内容了,因此我们删除了该类。
希望有帮助!
这篇文章,动态导入的想法(我认为)来自react-loadable。
https://turkus.github.io/2018/06/06/fouc-react/
| 归档时间: |
|
| 查看次数: |
3387 次 |
| 最近记录: |