如何访问 React Material-UI 主要和次要颜色的明暗变体?

And*_*ndy 5 reactjs material-ui

React 的 Material-UI 文档说主要和次要颜色的明暗变体将自动计算。

(来自文档:https : //material-ui.com/customization/palette/

const theme = createMuiTheme({
  palette: {
    primary: {
      // light: will be calculated from palette.primary.main,
      main: '#ff4400',
      // dark: will be calculated from palette.primary.main,
Run Code Online (Sandbox Code Playgroud)

我似乎找不到的是如何访问这些颜色以在我的组件中使用。在实现这样的主题之后:

const theme = createMuiTheme({
  palette: {
    secondary: {
      main: '#287a9f'
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

然后我将如何指定我想要一个组件使用辅助颜色的浅色变体?就像是:

<AppBar color="Primary.light" />
Run Code Online (Sandbox Code Playgroud)

我当然可以将它们手动实现为自定义颜色,但这似乎违背了自动计算的目的。

智慧大加赞赏。

Fra*_*ion 6

当您创建自定义主题时,将其传递给ThemeProvider这样的:

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
...

const theme = createMuiTheme({
  palette: {
    secondary: {
      main: '#287a9f'
    }
  }
});

function App() {

  return (
    <ThemeProvider theme={theme}>
      <Children />
    </ThemeProvider>
  )
}
Run Code Online (Sandbox Code Playgroud)

并且有很多方法可以访问主题变量,例如您可以使用makeStylesuseTheme

制作风格:

import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles(theme => ({
 myComp: { backgroundColor: theme.palette.primary.light }
});

function DeepChild() {
  const classes = useStyles();

  return <Component className={classes.myComp} />;
}
Run Code Online (Sandbox Code Playgroud)

使用主题:

import { useTheme } from '@material-ui/core/styles';

function DeepChild() {
  const theme = useTheme();

  return <Component color={theme.palette.primary.light} />;
}
Run Code Online (Sandbox Code Playgroud)

请注意,组件的color属性AppBar支持以下之一

["default","inherit","primary","secondary","transparent"]
Run Code Online (Sandbox Code Playgroud)

因此,为了覆盖AppBar组件的颜色,如您的示例中所示,您需要传递一个自定义类:

import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';

const useStyles = makeStyles(theme => ({
 appBar: { backgroundColor: theme.palette.primary.light }
});

function DeepChild() {
  const classes = useStyles();

  return <AppBar className={classes.appBar} />;
}
Run Code Online (Sandbox Code Playgroud)