我正在用 Gatsby 试验各种字体加载策略,最终解决了gatsby-plugin-theme-uitheme.fonts
的源代码,因此一旦客户端加载了所有字体(默认theme.fonts
设置为系统字体),我就可以更新值。
在完成所有这些之后,我ColorModeProvider
将其安装并添加wrap-root-element.js
到ThemeProvider
. 只有text
&background
颜色正在更新,但primary
,secondary
和muted
颜色没有改变(使用默认颜色)。我可以确认每次更改主题时 CSS 变量都会更新。
请让我知道我在这里缺少什么?
主题提供者:
/** @jsx jsx */
import { jsx, ThemeProvider } from 'theme-ui'
import { useState, useEffect, useCallback, Fragment } from 'react'
import theme from '../gatsby-plugin-theme-ui'
import components from '../gatsby-plugin-theme-ui/components'
import useEventListener from '../hooks/use-event-listener'
const themeUI = { ...theme }
const { fonts: { safe: safeFonts } } = { ...theme }
const safeFontsTheme = {
...Object.assign(
{},
theme,
{ fonts: safeFonts }
)
}
const ThemeUIProvider = ({ element }) => {
const [theme, setTheme] = useState(safeFontsTheme)
const updateTheme = useCallback(
() => {
setTheme(themeUI)
document.documentElement.classList.remove(
`font-loading-stage-1`,
`font-loading-stage-2`
)
},
[setTheme],
)
useEventListener(
typeof window !== 'undefined' && window,
'FONTS_ARE_LOADED',
updateTheme
)
useEffect(() => {
updateTheme()
sessionStorage.getItem('areFontsLoaded')
}, [updateTheme])
return (
<Fragment>
{jsx(ThemeProvider, {
theme,
components,
},
element
)}
</Fragment>
)
}
export default ThemeUIProvider
包装根元素.js:
/** @jsx jsx */
import { jsx } from 'theme-ui'
import { ColorModeProvider } from '@theme-ui/color-modes'
import PrismThemeProvider from './code-block/prism-theme-provider'
import ThemeUIProvider from './theme-ui-provider'
export const wrapRootElement = ({ element }) => {
return (
<PrismThemeProvider>
<ThemeUIProvider element={element}>
<ColorModeProvider>
{element}
</ColorModeProvider>
</ThemeUIProvider>
</PrismThemeProvider>
)
}
颜色模式按钮:
/** @jsx jsx */
import { jsx, IconButton, useColorMode } from 'theme-ui'
const ColorModeButton = props => {
const colorModes = [`default`, `dark`, `deep`, `swiss`]
const [colorMode, setColorMode] = useColorMode()
return (
<IconButton
{...props}
aria-label='Toggle website theme'
onClick={() => {
const index = colorModes.indexOf(colorMode)
const next = colorModes[(index + 1) % colorModes.length]
setColorMode(next)
}}
sx={{
cursor: 'pointer',
padding: 0,
width: 40,
height: 40,
marginX: 1,
}}
>
<svg
width='24'
height='24'
viewBox='0 0 32 32'
fill='currentcolor'
sx={{
display: 'flex',
margin: '0 auto',
transition: 'transform 400ms ease',
}}
>
<circle
cx='16'
cy='16'
r='14'
fill='none'
stroke='currentcolor'
strokeWidth='4'
></circle>
<path d='M 16 0 A 16 16 0 0 0 16 32 z'></path>
</svg>
</IconButton>
)
}
export default ColorModeButton