我有一个用 React Static 构建的网站,它有一个始终存在的 Header 组件。根据当前页面是否具有主图组件,页眉应为浅色或深色。
标头在路由外部呈现,并在呈现子级之前触发useEffect
。这可能是因为路由。
这是当前代码:
// App.js
import React, { useState, useEffect } from 'react'
import { Root, Routes } from 'react-static'
export default () => {
const [useDarkTheme, setUseDarkTheme] = useState(false);
useEffect(() => {
if (typeof document !== "undefined") {
const heroPresent = document.querySelectorAll(".o-hero").length > 0;
console.log("The hero is present: " + heroPresent);
setUseDarkTheme(!heroPresent);
}
})
return (
<Root>
<React.Suspense fallback={ <em>Loading...</em> }>
<Header useDarkTheme={ useDarkTheme } />
<Routes default />
</React.Suspense>
</Root>
);
}
<Routes default />
将呈现的是 React Staticstatic.config.js
中配置的静态页面。
下面是主组件的示例:
// Hero.js
import React from "react";
export default () => {
console.log("This is the Hero rendering. If this exist, the Header should be dark.");
return (
<div className="o-hero">
<p>Hero!</p>
</div>
);
}
当我运行应用程序并查看日志时,这就是我得到的:
The hero is present: false
This is the Hero rendering. If this exist, the Header should be dark.
我如何以某种方式从标头中检测到英雄的存在,尽管英雄在路由器中而标头不在?这感觉像是一个很常见的用例,但我在互联网上找不到任何信息。
提前感谢!
所以我最终使用useContext
为所有孩子提供标题主题(深色或浅色(的 getter 和 setter。解决方案在很大程度上受到这个答案的启发。 解决方案如下所示:
// App.js
import React, { useState, useContext } from 'react'
import { Root, Routes } from 'react-static'
import { HeaderThemeContext } from "./context";
export default () => {
const { theme } = useContext(HeaderThemeContext);
const [headerTheme, setHeaderTheme] = useState(theme);
return (
<Root>
<React.Suspense fallback={ <em>Loading...</em> }>
<HeaderThemeContext.Provider value={ { theme: headerTheme, setTheme: setHeaderTheme } }>
<Header theme={ headerTheme } />
<Routes default />
</HeaderThemeContext.Provider>
</React.Suspense>
</Root>
);
}
// Hero.js
import React from "react";
import { headerThemes, setHeaderTheme } from "./context";
export default () => {
setHeaderTheme(headerThemes.DARK);
console.log("This is the Hero rendering. If this exist, the Header should be dark.");
return (
<div className="o-hero">
<p>Hero!</p>
</div>
);
}
// context.js
import React, { createContext, useContext } from "react";
export const headerThemes = {
LIGHT: "light",
DARK: "dark",
};
export const HeaderThemeContext = createContext({
theme: headerThemes.LIGHT,
setTheme: () => {}
});
// This is a hook and can only be used in a functional component with access to the HeaderThemeContext.
export const setHeaderTheme = theme => useContext(HeaderThemeContext).setTheme(theme);
这提供了全局访问权限来设置和获取标题主题,这可能不是可选的,但它现在有效,我认为这很好。请让我知道是否有更好的方法。