跳到内容
+

使用 CSS 变量

了解如何使用 CSS 变量来自定义 Joy UI 组件。

简介

要使用 CSS 变量,您必须使用 <CssVarsProvider /> 实用程序包裹您的应用。

import { CssVarsProvider } from '@mui/joy/styles';

function App() {
  return <CssVarsProvider>...</CssVarsProvider>;
}

然后您可以使用 theme.vars.* 表示法应用基于 CSS 变量的样式。Joy UI 支持的所有样式 API 均可使用此表示法,包括 styled() 函数和 sx 属性。

样式 API

theme.vars.* 表示法与 Joy UI 支持的任何样式 API 一起使用

styled 函数

const Div = styled('div')(({ theme }) => ({
  // Outputs 'var(--joy-palette-primary-500)'
  color: theme.vars.palette.primary[500],
}));

sx 属性

// Outputs 'var(--joy-shadow-sm)'
<Chip sx={(theme) => ({ boxShadow: theme.vars.shadow.sm })} />

您还可以使用简写语法从 theme.vars.* 解析值,方式与上面的示例相同。

<Chip
  sx={{
    border: '1px solid',

    // For color properties, lookup from `theme.vars.palette`
    color: 'neutral.800', // 'var(--joy-palette-neutral-800)'
    borderColor: 'neutral.400', // 'var(--joy-palette-neutral-400)'

    // lookup from `theme.vars.shadow`
    shadow: 'sm', // 'var(--joy-shadow-sm)'

    // lookup from `theme.vars.fontSize`
    fontSize: 'sm', // 'var(--joy-fontSize-sm)'
  }}
/>

主题化组件

extendTheme({
  components: {
    JoyButton: {
      root: ({ theme }) => ({
        // Outputs 'var(--joy-fontFamily-display)'
        fontFamily: theme.vars.fontFamily.display,
      }),
    },
  },
});

useTheme 钩子

import { useTheme } from '@mui/joy/styles';

const SomeComponent = () => {
  const theme = useTheme(); // The runtime theme.

  return (
    <div>
      <p style={{ color: {theme.vars.palette.primary[500]} }}>Some text here.</p>
    </div>
  );
};

创建新变量

要创建新的 CSS 变量,请使用原始主题值(theme.* 而不是 theme.vars.*)。下面的代码示例展示了如何创建一个新的阴影主题值

const Div = styled('div')(({ theme }) => ({
  // Note that it's using `theme.shadow`, not `theme.vars.shadow`
  boxShadow: theme.shadow.sm.replace(/,/g, ', inset'),
}));

调整颜色不透明度

使用自动生成的透明通道令牌(mainChannellightChanneldarkChannel),以及 rgba 颜色表示法,来调整 Joy UI 中所有可用调色板中的颜色不透明度。

const Div = styled('div')(({ theme }) => ({
  backgroundColor: `rgba(${theme.vars.palette.primary.mainChannel} / 0.2)`,
}));

自定义前缀

默认情况下,每个 Joy UI CSS 变量都以 joy 为前缀。要更改此前缀,请在 <CssVarsProvider /> 组件上的 extendTheme 函数内使用 cssVarPrefix 属性。

import { CssVarsProvider, extendTheme } from '@mui/joy/styles';

function App() {
  return (
    <CssVarsProvider theme={extendTheme({ cssVarPrefix: 'company' })}>
      ...
    </CssVarsProvider>
  );
}

然后生成的 CSS 变量将是

- --joy-fontSize-md: 1rem;
+ --company-fontSize-md: 1rem;

移除默认前缀

cssVarPrefix 属性中使用空值 ('') 以从生成的 CSS 变量中移除默认的 joy 前缀

import { CssVarsProvider, extendTheme } from '@mui/joy/styles';

function App() {
  return (
    <CssVarsProvider theme={extendTheme({ cssVarPrefix: '' })}>...</CssVarsProvider>
  );
}
- --joy-fontSize-md: 1rem;
+ --fontSize-md: 1rem;