代码之家  ›  专栏  ›  技术社区  ›  JacobIRR

如何将材质UI主题传递给许多“路由”组件

  •  0
  • JacobIRR  · 技术社区  · 6 年前

    withStyles withTheme ,但我认为它们不适用于 ReactDOM.render . 有没有办法让我的自定义主题可以从所有组件访问?

    const theme = createMuiTheme({/*... lots of theme code here */});
    
    const app = signalRConnection => (
      <SignalRProvider connection={signalRConnection}>
        <CssBaseline />
        <MuiThemeProvider theme={theme}>
        <Router history={createBrowserHistory()}>
          <Switch>
            <Route exact path="/" component={DashboardPage} />
            <Route path="/foo/:id" component={FooPage} />
            <Route path="/test" component={TestPage} />
            <Route path="/home/chat" component={ChatApp} />
            <Route render={() => <Redirect to="/" />} />
          </Switch>
        </Router>
        </MuiThemeProvider>
      </SignalRProvider>
    );
    
    window.renderApp = function(id, signalRConnection) {
      ReactDOM.render(app(signalRConnection), document.getElementById(id));
    };
    

    <Route
      path='/'
      component={() => <DashboardPage theme={theme} />}
    />
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Ryan Cogswell    6 年前

    MuiThemeProvider 使主题可供所有子体组件使用,因此无需执行任何额外操作即可使主题可用(您的管线都已是的子体) 音乐提供者 withTheme withStyles 在组件中(例如。 DashboardPage )这需要使用主题。

    如果您希望能够以道具的形式访问主题 仪表板页面 可能看起来像:

    import React from "react";
    import { withTheme } from "@material-ui/core/styles";
    import Button from "@material-ui/core/Button";
    const DashboardPage = ({ theme }) => {
      return (
        <>
          <div>Primary color is {theme.palette.primary.main}</div>
          <Button color="primary" variant="contained">
            Show Theme in a Button
          </Button>
        </>
      );
    };
    const DashboardPageWithTheme = withTheme()(DashboardPage);
    export default DashboardPageWithTheme;
    

    下面是一个工作示例:

    Edit ywx1nvvy6z