嗨,按照标题,我想根据使用不同主题提供者的路线,我的代码如下所示:
const rootElement = document.getElementById('root');
ReactDOM.render(
<ThemeProvider theme="MyThemes.default">
<CssBaseline />
<App />、rootElement,);
哪里
const myThemes= {
default: createMuiTheme({ ...defaultTheme, ...typography, overrides: { ...muiCssBaseline,
...muiTableOverrides } }),
myother_theme: createMuiTheme({ ...myOtherTheme, ...typography, overrides: {
...muiCssBaseline, ...muiTableOverrides } }),};
所以,当我在一个特定的路线上,我想使用myother_theme
我正在制作一个包装组件,以便像这样调用index.js
const ThemeProviderChange = ({ children }) => {
const [theme, setTheme] = useState(Themes.default);
const isMyLocation= window.location.pathname === "/MYlOCATION/PATH"?? true;
const url = window.location.pathname.split('/').pop();
useEffect(() => {
if (isMyLocation) {
setTheme(MyThemes.myother_theme);
} else {
setTheme(MyThemes.default);
}
}, [url]);
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};
export default ThemeProviderChange;但是要想工作,需要用户进行手动刷新。有什么建议吗?
发布于 2022-02-01 04:37:09
useEffect钩子中的数组依赖不使用窗口进行调度。为此,您应该使用useLocation的react路由器-dom。
我用这个例子https://codesandbox.io/s/custom-theme-provider-mui-based-in-routes-tt1d4来解决这个问题。
const location = useLocation();
const isMyLocation = location.pathname === "/MYlOCATION/PATH";
useEffect(() => {
if (isMyLocation) {
setTheme(MyThemes.myother_theme);
} else {
setTheme(MyThemes.default);
}
}, [location.pathname, isMyLocation]);此外,您还需要在app中添加BrowserRouter包装器上下文,以侦听状态路由中的更改。
https://stackoverflow.com/questions/70928581
复制相似问题