直接在material-ui的主题配置中支持渐变

Abh*_*kar 4 reactjs material-design material-ui

现在我们可以在 material-ui 中配置主题如下。

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

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#ff4400'
    },
    secondary: {
      light: '#0066ff',
      main: '#0044ff',
      contrastText: '#ffcc00',
    },
    // error: will use the default color
  },
});
Run Code Online (Sandbox Code Playgroud)

有没有办法为原色和副色提供渐变配置?恕我直言,微妙的渐变提供了更好的颜色流行并使平面颜色稍微不那么无聊

str*_*tss 9

您可以在主题内设置渐变值:

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#ff4400',
      mainGradient: "linear-gradient(to right, tomato, cyan)",
    },
    // ...
  },
});
Run Code Online (Sandbox Code Playgroud)

然后在 components styleprop 中使用这个值:

<AppBar
  position="static"
  style={{ background: theme.palette.primary.mainGradient }}
> ...
Run Code Online (Sandbox Code Playgroud)

编辑

这确实让人感觉很棘手,但我相信这是目前唯一的方法。我在 MUI 文档中没有找到任何这样的例子。如果您查看组件的来源<AppBar />,您会发现无法使用main,lightdark颜色作为线性渐变:

export const styles = theme => {
  //...

  return {
    /* ... */

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {
      backgroundColor: theme.palette.primary.main, 
      color: theme.palette.primary.contrastText,
    },
    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      backgroundColor: theme.palette.secondary.main,
      color: theme.palette.secondary.contrastText,
    },
  };
};
Run Code Online (Sandbox Code Playgroud)

如您所见backgroundColor,此处使用。设置linear-gradient(...)为无效。