有没有办法在运行时更新 Material UI 主题调色板的主要颜色和次要颜色?

Is there a way to update Material UI theme palette primary and secondary color at runtime?

我们的应用程序中有一组默认的主题调色板颜色,但是出于白色标签的目的,我从 API 中获取主题主色和辅助色。在收到 API?

的值后,有什么方法可以在运行时更新这些颜色

我在应用级别包装 MUI themeProvider

import { ThemeProvider, StylesProvider } from '@material-ui/styles';
 import { createMuiTheme } from '@material-ui/core';
 
 
 const App = () => {
const customTheme = createMuiTheme({
  palette: {
   primary: {
      main: "#fff0c9", 
   },
   secondary: {
      main: '#FF8200',
   }
});
 
return(
    <ThemeProvider theme={customTheme}> 
      <div> Component </div>
   </ThemeProvider>)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

加载组件后,API 调用会接收每个客户端更新的主要颜色和次要颜色。有没有办法在运行时更新它?

您可以在状态中存储所需的颜色并使用新颜色更新该状态。然后,您在 createMuiTheme() 中使用该状态来设置主要颜色和次要颜色。您可能还想使用 React.memo().

下面是设置随机颜色的示例:

const { useMemo, useState } = React;
const {
  AppBar,
  Button,
  createMuiTheme,
  CssBaseline,
  ThemeProvider,
  Toolbar
 } = MaterialUI;
 
const randomColor = () =>
  `#${Math.floor(Math.random() * 16777215).toString(16)}`;

const App = () => {
  const [primary, setPrimary] = useState(randomColor);

  const theme = useMemo(
    () =>
      createMuiTheme({
        palette: {
          primary: { main: primary }
        }
      }),
    [primary]
  );

  const setRandomPrimary = () => setPrimary(randomColor);

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <AppBar color="primary">
        <Toolbar />
      </AppBar>
      <Toolbar />
      <Button onClick={setRandomPrimary}>Change Color</Button>
    </ThemeProvider>
  );
}

ReactDOM.render(<App />, document.body);
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.production.min.js"></script>

这是基于此documentation

随机颜色函数来自CSS-Tricks