如何在Gatsby.js的body标签中添加动态类? [英] How to add a dynamic class to body tag in Gatsby.js?

查看:81
本文介绍了如何在Gatsby.js的body标签中添加动态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,这不是一件容易的事,因为 html.js 模板文件中唯一更改的默认内容是head meta标签和内容.

Obviously, that's not an easy task, as the only thing that changes in the html.js template file by default are the head meta tags and the content.

元标记由头盔组件( {head.title.toComponent()} {head.meta.toComponent()} )和HTML处理模板内部的更改由React管理.(< div id ="react-mount"危险地设置为InnerHTML = {{__html:this.props.body}}/> )

The meta tags are handled by the Helmet component ({head.title.toComponent()} and {head.meta.toComponent()}) and the HTML changes inside the template are managed by React. (<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />)

body标记超出了React的范围,这就是为什么当我在页面之间导航时,我不知道如何即时更改它的原因.这正是我所需要的,因为我想在每个页面上应用不同的正文背景.

The body tag however is outside the scope of React, which is why I can't figure out how to change it on-the-fly when I navigate from page to page. That's exactly what I'd need though as I wanna apply a different body background to each page.

我知道我可以通过使用 gatsby-browser.js 中的 exports.onRouteUpdate 解决此问题,但是即使JS是在浏览器中禁用.意味着即使我导出时没有 bundle.js 文件,而只是生成静态网站HTML,我也希望它在那里.

I know that I could solve this by using the exports.onRouteUpdate in gatsby-browser.js, but I would like the class to be present even if JS is disabled in the browser. Means I'd like it to be there even if I export without the bundle.js file, just generating the static site HTML.

推荐答案

它看起来确实像react-helmet支持在< html> 元素上动态/静态地设置一个类.

It does look like react-helmet supports dynamically/statically setting a class on the <html> element.

尽管他们不希望在身体上支持设置类... https://github.com/nfl/react-helmet/issues/182

They don't want to support setting classes on the body though... https://github.com/nfl/react-helmet/issues/182

如果您确实需要支持主体类,则此模块的功能与react-helmet非常相似,但对于主体类 https://github.com/iest/react-body-classname

If you really need to support body classes, then this module does something very similar to react-helmet but for body classes https://github.com/iest/react-body-classname

这篇关于如何在Gatsby.js的body标签中添加动态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆