【发布时间】:2022-01-09 11:14:14
【问题描述】:
我只是出于好奇而玩 Material UI 5 sx 道具,不明白如何使它类似于以前的 MUI 4 makeStyles fn。我正在尝试将 JSS classnemaes 传递给 sx 道具。所以在这段代码 sn-p 中,我想覆盖偶数字符串的颜色:
import { Typography } from "@mui/material";
const styles = {
green: {
color: 'green',
},
red: {
color: 'red',
},
}
const options = ['even', 'odd', 'even', 'odd']
export default function CssModulesSlider() {
console.log('classes', styles)
return (
<>
{options.map((item, index)=> {
if(index %2 === 0){
return (
<Typography sx={{...styles.red}}>
{item}
</Typography>
)
} else {
return (
<Typography sx={{...styles.red, ...styles.green,}}>
{item}
</Typography>
)
}
})}
</>
);
}
MUI 将其编译为不同的 CSS 类:
.css-**1kivl2a**-MuiTypography-root {
//some mui typography stuff here
color: red;
}
.css-**1ti676r**-MuiTypography-root {
//some mui typography stuff here
color: green;
}
在this codesandbox example 中一切正常,
直到我改变了 sx props 中定义类的顺序:
//from
sx={{...styles.red, ...styles.green,}}
//to
sx={{...styles.green, ...styles.red,}}
虽然样式对象仍然与您在 console.log 中看到的相同,但 MUI 将其全部编译为一个 CSS 类,因此所有列表项都具有相同的类,并带有 color: red 规则。 这与 CSS 规则的覆盖无关,取决于它的顺序,因为在第二种情况下,编译后的 CSS 中的类是相同的
当然最好使用 CSS 模块、情感或样式组件。但是有人知道为什么会这样吗?
【问题讨论】:
标签: css reactjs material-ui jss sx