首页 > 解决方案 > 如何在 MUI 5 的断点属性中访问主题?

问题描述

我需要theme.spacing在我的sm断点中使用 my ,但没有任何尝试有效。

sx={{
  paddingTop: { sm: 0 },
  paddingRight: { sm: "spacing(6)" },
  paddingBottom: { sm: "spacing(10)" },
  paddingLeft: { sm: "theme.spacing(6)" },
  "@media screen and (orientation:landscape)": {
    paddingTop: { sm: 0 },
    paddingRight: { sm: "spacing(6)" },
    paddingBottom: { sm: "spacing(2)" },
    paddingLeft: { sm: "theme.spacing(6)" },
  },
}}

或这个

sx={{
  paddingTop: { sm: 0 },
  paddingRight: { sm: (theme) =>  theme.spacing(6) },
  paddingBottom: { sm: (theme) =>  theme.spacing(10) },
  paddingLeft: { sm: (theme) =>  theme.spacing(6) },
  "@media screen and (orientation:landscape)": {
    paddingTop: { sm: 0 },
    paddingRight: { sm: (theme) =>  theme.spacing(6) },
    paddingBottom: { sm: (theme) =>  theme.spacing(2) },
    paddingLeft: { sm: (theme) =>  theme.spacing(6) },
  },
}}

如何使用带断点的主题值(sm、、、mdlg

标签: reactjsmaterial-uisx

解决方案


CSS 属性支持使用主题的回调语法(甚至嵌套在媒体查询中),但不支持将其作为断点键的值。下面的示例展示了在多个级别使用回调语法——作为顶级属性的值 ( padding),作为顶级媒体查询的值(横向),以及作为其中指定的属性的值媒体查询(paddingTop纵向内)。

import * as React from "react";
import Box from "@mui/material/Box";
import { Theme } from "@mui/material/styles";

export default function SxWithOrientation() {
  return (
    <div>
      <Box
        sx={{
          border: "solid 1px black",
          padding: (theme: Theme) => theme.spacing(5),
          "@media screen and (orientation: landscape)": (theme: Theme) => ({
            color: "black",
            paddingTop: {
              xs: theme.spacing(2.5),
              sm: 3,
              md: 4,
              lg: 5,
              xl: 6
            },
            backgroundColor: {
              xs: "lightgray",
              sm: "lightblue",
              md: "lightgreen",
              lg: "pink",
              xl: "orange"
            }
          }),
          "@media screen and (orientation: portrait)": {
            color: "white",
            paddingTop: (theme: Theme) => ({
              xs: theme.spacing(5.5),
              sm: 4,
              md: 3,
              lg: 2
            }),
            backgroundColor: {
              xs: "black",
              sm: "blue",
              md: "green",
              lg: "red"
            }
          }
        }}
      >
        This box has responsive padding and colors.
      </Box>
    </div>
  );
}

使用带有 sx 道具的回调进行编辑


推荐阅读