如何通过 MUI 5 SX prop 使用多个 CSS 类?

syb*_*oda 11 javascript reactjs material-ui

有谁知道如何通过 MUI 5 SX prop 使用多个 CSS 类?我创建了一个基类,我想将其与 Box 组件一起使用,但使用第二个类专门用于 Box 内部的文本。应用基类,例如sx={styles.baseBoxStyle}可以工作但sx={styles.baseBoxStyle styles.customBoxFontStyle}返回错误。下面提供了完整的代码片段和沙箱。非常感谢任何帮助!

沙盒:https://codesandbox.io/s/mui-5-styling-uqt9m?file =/pages/index.js

import * as React from "react";
import Box from "@mui/material/Box";

const styles = {
  baseBoxStyle: {
    backgroundColor: "red",
    borderRadius: "20px 20px 20px 20px",
    border: "1px solid black",
    maxWidth: "150px",
    margin: "20px",
    padding: "10px"
  },
  customBoxFontStyle: {
    color: "yellow",
    fontWeight: "bold"
  }
};

export default function Index() {
  return <Box sx={styles.baseBoxStyle styles.customBoxFontStyle}>This is a test</Box>;
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 13

我遇到了类似的问题并提出了这个解决方案。

  <Box sx={[styles.baseBoxStyle, styles.customBoxFontStyle]}>
    This is a test
  </Box>
Run Code Online (Sandbox Code Playgroud)

https://codesandbox.io/s/sweet-blackwell-oqp9ph?file=/src/App.js:416-517


ham*_*nia 11

如果你想组合 2 个类,并且你得到其中一个作为道具,你应该像这样工作

const componnent = (styles) => {
 return ( 
  <ListItem
    sx={[
      {
        width: 'auto',
        textDecoration: 'underline',
      },
      ...(Array.isArray(styles) ? styles : [styles]),
    ]}
  /> 
 )
}

Run Code Online (Sandbox Code Playgroud)

不能sx直接传播,因为SxProps(typeof sx) 可以是数组


Min*_*lsh 5

对于一种简单的解决方案,可以解构样式对象并编译为一个对象。

<Box sx={{...styles.baseBoxStyle,...styles.customBoxFontStyle}}>This is a test</Box>


Wra*_*thy 3

您可以尝试使用类名作为其常用库,或者您可以从传递给 sx 的这些样式中创建字符串sx={styles.baseBoxStyle+' '+styles.customBoxFontStyle}

  • 哦,抱歉,我不知道为什么我想,这些是类...但是您可以尝试组合这两个对象: `sx={{...styles.baseBoxStyle,...styles.customBoxFontStyle}}` (3认同)