我如何在材质UI样式对象中提出共同规则?



我有以下一组样式规则:

status_in_progress: {
fontSize: 14,
backgroundColor: theme.palette.success.dark,
padding: 2,
paddingLeft: 5,
paddingRight: 5,
display: "inline-block",
},
status_complete: {
fontSize: 14,
backgroundColor: theme.palette.primary.dark,
padding: 2,
paddingLeft: 5,
paddingRight: 5,
display: "inline-block",
},
status_overdue: {
fontSize: 14,
backgroundColor: theme.palette.error.dark,
padding: 2,
paddingLeft: 5,
paddingRight: 5,
display: "inline-block",
},

正如您所看到的,其中大部分是相同的。我希望能够定义一组这样的规则:

status: {
fontSize: 14,
padding: 2,
paddingLeft: 5,
paddingRight: 5,
display: "inline-block",
in_progress: {
backgroundColor: theme.palette.success.dark,
},
complete: {
backgroundColor: theme.palette.primary.dark,
},
...
},

但MUI似乎不喜欢这样。提出共同规则的最有效方法是什么?

我也在使用ReactJS。

当我们在JS对象中编写CSS样式时,对象的键被解析以找到相应的CSS属性。例如,在您的status对象中,键fontSize被解析为font-size,这是一个有效的CSS属性。

但是,在您重构的代码中,您包含了in_progresscomplete的键,它们不对应于任何有效的CSS属性。因此,解析器很难理解您试图用这些键实现的目的。

你可以尝试下面的重构:

import React from "react";
import clsx from "clsx";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
status: {
fontSize: 14,
padding: 2,
paddingLeft: 5,
paddingRight: 5,
display: "inline-block",
},
in_progress: {
backgroundColor: theme.palette.success.dark,
},
complete: {
backgroundColor: theme.palette.primary.dark,
},
overdue: {
backgroundColor: theme.palette.error.dark,
}
});
function ExampleComponent(props) {
const classes = useStyles(props);
return (
<div>
<p className={clsx(classes.status, classes.in_progress)}>Sample Text</p>
</div>
)
}

我将in_progress,completeoverdue键移出status对象。

在我的示例代码中,我向一个元素添加了classes.statusclasses.in_progress两个类。这相当于在重构代码之前添加classes.status_in_progress:

<p className={clsx(classes.status, classes.in_progress)}>Sample Text</p>

请注意,clsx()是一个很小的实用程序,它是预先安装在您的项目中,允许您更容易地构建className字符串。clsx的repo列出了更多关于如何使用它的示例。如果你不想使用clsx(),下面的代码是一样的:

<p className={`${classes.status} ${classes.in_progress}`}>Sample Text</p>

我更喜欢clsx(),因为模板字符串语法有时会变得乏味。如果您想使用clsx(),请记住导入它通过在文件顶部添加import clsx from "clsx";

最新更新