GatsbyJS:替换部分服务器端呈现 html
GatsbyJS: Replace part of the server side rendered html
我的 React 应用程序中有一个倒计时组件,当倒计时尚未到达目标日期时,<html>
应该有一个 class is-counting
否则它应该有class is-complete
.
实现是这样的:(使用包react-helmet
)
<Countdown toDate={new Date(2019, 5, 14)}>
{props =>
props.isComplete ? (
<Helmet htmlAttributes={{ class: 'is-complete' }} />
) : (
<Helmet htmlAttributes={{ class: 'is-counting' }} />
)
}
</Countdown>;
所以当我 运行 gatsby build
服务器端呈现 html 时 class is-counting
像这样:
<html class="is-counting">…</html>
我的问题是,删除应用于 <html>
标签的 class 的最佳方法是什么?我需要不应用 class 否则我在页面加载时的转换将不起作用,只有当 javascript 开始到 运行.
时才应应用它们
我认为答案在文档的这一部分:SSR APIs | GatsbyJS 但我不确定具体如何进行。
提前致谢。
所以,按照 @xadm 建议我让它工作,我在倒计时的状态中添加了 isClient
,该状态最初设置为 false
,然后在 componentDidMount
中我设置它到 true
(在执行 ssr 时不会调用此生命周期方法)所以现在我只是将它作为 prop 传递并有条件地渲染组件:
<Countdown toDate={new Date(2019, 5, 14)}>
{props =>
props.isComplete ? (
{props.isClient && (
<Helmet htmlAttributes={{ class: 'is-complete' }} />
)}
) : (
{props.isClient && (
<Helmet htmlAttributes={{ class: 'is-counting' }} />
)}
)
}
</Countdown>
这样 class 仅应用于客户端,我在页面加载时的转换效果很好。
编辑:经过一番思考后,我将 isClient
状态添加到根组件,因为:
- 把它放在那里比倒计时本身更有意义
- 如果需要,它可以很容易地被应用程序的其他部分使用
我的 React 应用程序中有一个倒计时组件,当倒计时尚未到达目标日期时,<html>
应该有一个 class is-counting
否则它应该有class is-complete
.
实现是这样的:(使用包react-helmet
)
<Countdown toDate={new Date(2019, 5, 14)}>
{props =>
props.isComplete ? (
<Helmet htmlAttributes={{ class: 'is-complete' }} />
) : (
<Helmet htmlAttributes={{ class: 'is-counting' }} />
)
}
</Countdown>;
所以当我 运行 gatsby build
服务器端呈现 html 时 class is-counting
像这样:
<html class="is-counting">…</html>
我的问题是,删除应用于 <html>
标签的 class 的最佳方法是什么?我需要不应用 class 否则我在页面加载时的转换将不起作用,只有当 javascript 开始到 运行.
我认为答案在文档的这一部分:SSR APIs | GatsbyJS 但我不确定具体如何进行。
提前致谢。
所以,按照 @xadm 建议我让它工作,我在倒计时的状态中添加了 isClient
,该状态最初设置为 false
,然后在 componentDidMount
中我设置它到 true
(在执行 ssr 时不会调用此生命周期方法)所以现在我只是将它作为 prop 传递并有条件地渲染组件:
<Countdown toDate={new Date(2019, 5, 14)}>
{props =>
props.isComplete ? (
{props.isClient && (
<Helmet htmlAttributes={{ class: 'is-complete' }} />
)}
) : (
{props.isClient && (
<Helmet htmlAttributes={{ class: 'is-counting' }} />
)}
)
}
</Countdown>
这样 class 仅应用于客户端,我在页面加载时的转换效果很好。
编辑:经过一番思考后,我将 isClient
状态添加到根组件,因为:
- 把它放在那里比倒计时本身更有意义
- 如果需要,它可以很容易地被应用程序的其他部分使用