跳到内容
+

sx 属性

sx 属性是用于定义可以访问主题的自定义样式的快捷方式。

sx 属性允许您使用 CSS 的超集,其中打包了 @mui/system 中公开的所有样式功能。您可以使用此属性指定任何有效的 CSS,以及许多 MUI System 独有的主题感知属性。

基本示例

以下演示说明了如何使用 sx 属性。请注意,并非所有值都是有效的 CSS 属性——这是因为 sx 键映射到主题的特定属性。本文档的其余部分将更详细地探讨这个概念。

会话
98.3 K
+18.77%
与上周相比
Enter 开始编辑

主题感知属性

边框

border 属性只能接收数字作为值。它创建一个黑色实线边框,使用该数字定义像素宽度

<Box sx={{ border: 1 }} />
// equivalent to border: '1px solid black'

borderColor 属性可以接收字符串,该字符串表示 theme.palette 中的路径

<Box sx={{ borderColor: 'primary.main' }} />
// equivalent to borderColor: theme => theme.palette.primary.main

borderRadius 属性将接收到的值乘以 theme.shape.borderRadius 值(此值的默认值为 4px)。

<Box sx={{ borderRadius: 2 }} />
// equivalent to borderRadius: theme => 2 * theme.shape.borderRadius

阅读边框页面了解更多信息。

显示

displayPrint 属性允许您指定一个 CSS display 值,该值仅在打印时应用

<Box sx={{ displayPrint: 'none' }} /> // equivalent to '@media print': { display: 'none' }

阅读显示页面了解更多信息。

网格

CSS Grid 属性 gaprowGapcolumnGap 将它们接收到的值乘以 theme.spacing 值(该值的默认值为 8px)。

<Box sx={{ gap: 2 }} />
// equivalent to gap: theme => theme.spacing(2)

阅读网格页面了解更多信息。

调色板

colorbackgroundColor 属性可以接收字符串,该字符串表示 theme.palette 中的路径

<Box sx={{ color: 'primary.main' }} />
// equivalent to color: theme => theme.palette.primary.main

backgroundColor 属性也可以通过其别名 bgcolor 使用

<Box sx={{ bgcolor: 'primary.main' }} />
// equivalent to backgroundColor: theme => theme.palette.primary.main

阅读调色板页面了解更多信息。

位置

zIndex 属性将其值映射到 theme.zIndex

<Box sx={{ zIndex: 'tooltip' }} />
// equivalent to zIndex: theme => theme.zIndex.tooltip

阅读位置页面了解更多信息。

阴影

boxShadow 属性将其值映射到 theme.shadows

<Box sx={{ boxShadow: 1 }} />
// equivalent to boxShadow: theme => theme.shadows[1]

阅读阴影页面了解更多信息。

尺寸

尺寸属性 widthheightminHeightmaxHeightminWidthmaxWidth 对值使用以下自定义转换函数

function transform(value) {
  return value <= 1 && value !== 0 ? `${value * 100}%` : value;
}

如果值在 (0, 1] 之间,则将其转换为百分比。否则,它将直接在 CSS 属性上设置

<Box sx={{ width: 1/2 }} /> // equivalent to width: '50%'
<Box sx={{ width: 20 }} /> // equivalent to width: '20px'

阅读尺寸页面了解更多信息。

间距

间距属性 marginpadding 以及相应的简写属性将它们接收到的值乘以 theme.spacing 值(该值的默认值为 8px

<Box sx={{ margin: 2 }} />
// equivalent to margin: theme => theme.spacing(2)

以下别名可用于间距属性

属性 CSS 属性
m margin
mt margin-top
mr margin-right
mb margin-bottom
ml margin-left
mx margin-left, margin-right
my margin-top, margin-bottom
p padding
pt padding-top
pr padding-right
pb padding-bottom
pl padding-left
px padding-left, padding-right
py padding-top, padding-bottom

阅读间距页面了解更多信息。

排版

fontFamilyfontSizefontStylefontWeight 属性将其值映射到 theme.typography

<Box sx={{ fontWeight: 'fontWeightLight' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight

通过省略 CSS 属性前缀 fontWeight 也可以实现相同的效果

<Box sx={{ fontWeight: 'light' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight

还有一个额外的 typography 属性可用,它设置在特定 theme.typography 变体中定义的所有值

<Box sx={{ typography: 'body1' }} />
// equivalent to { ...theme.typography.body1 }

阅读排版页面了解更多信息。

响应式值

sx 属性关联的所有属性也支持特定断点和容器查询的响应式值。

阅读用法页面—响应式值了解更多信息。

回调值

当您需要获取作为对象的主题值时,请使用回调

<Box
  sx={(theme) => ({
    ...theme.typography.body,
    color: theme.palette.primary.main,
  })}
/>

在 TypeScript 中,要将自定义主题属性与 sx 属性回调一起使用,请使用模块扩充@mui/system 库扩展 Theme 类型

import * as React from 'react';
import Box from '@mui/material/Box';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { orange } from '@mui/material/colors';

declare module '@mui/system' {
  interface Theme {
    status: {
      warning: string;
    };
  }
}

const theme = createTheme({
  status: {
    warning: orange[500],
  },
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={(theme) => ({
          bgcolor: theme.status.warning,
        })}
      >
        Example
      </Box>
    </ThemeProvider>
  );
}

数组值

当您想要部分覆盖前一个索引中的某些样式时,数组类型很有用

<Box
  sx={[
    {
      '&:hover': {
        color: 'red',
        backgroundColor: 'white',
      },
    },
    foo && {
      '&:hover': { backgroundColor: 'grey' },
    },
    bar && {
      '&:hover': { backgroundColor: 'yellow' },
    },
  ]}
/>

当您悬停在此元素上时,将应用 color: red; backgroundColor: white;

如果 foo: true,则悬停时应用 color: red; backgroundColor: grey;

如果 bar: true,则悬停时应用 color: red; backgroundColor: yellow;,而与 foo 值无关,因为数组的较高索引具有更高的特异性。

<Box
  sx={[
    { mr: 2, color: 'red' },
    (theme) => ({
      '&:hover': {
        color: theme.palette.primary.main,
      },
    }),
  ]}
/>

传递 sx 属性

如果您想从自定义组件接收 sx 属性并将其传递给另一个 MUI System,我们建议使用这种方法

  • Enter 开始编辑

    动态值

    对于高度动态的 CSS 值,我们建议使用内联 CSS 变量,而不是在每次渲染时将具有不同值的对象传递给 sx 属性。这种方法避免了在 DOM 中插入不必要的 style 标签,从而防止在处理可以容纳各种频繁变化的值的 CSS 属性时出现潜在的性能问题——例如,带有实时预览的颜色选择器。

    TypeScript 用法

    sx 属性的一个常见混淆来源是 TypeScript 的类型拓宽,这会导致此示例无法按预期工作

    const style = {
      flexDirection: 'column',
    };
    
    export default function App() {
      return <Button sx={style}>Example</Button>;
    }
    
    // Type '{ flexDirection: string; }' is not assignable to type 'SxProps<Theme> | undefined'
    // Type '{ flexDirection: string; }' is not assignable to type 'CSSSelectorObject<Theme>'
    //   Property 'flexDirection' is incompatible with index signature
    //     Type 'string' is not assignable to type 'SystemStyleObject<Theme>'
    

    问题是 flexDirection 属性的类型被推断为 string,这太宽泛了。要解决此问题,您可以将传递给 sx 属性的对象/函数强制转换为 const

    const style = {
      flexDirection: 'column',
    } as const;
    
    export default function App() {
      return <Button sx={style}>Example</Button>;
    }
    

    或者,您可以将样式对象直接传递给 sx 属性

    export default function App() {
      return <Button sx={{ flexDirection: 'column' }}>Example</Button>;
    }
    

    性能

    要了解有关 sx 属性的性能权衡的更多信息,请查看用法 – 性能权衡