我正在使用 Material UI,我想使用 styled API 的多个规则名称来设置组件样式.
假设我想设置 FormLabel Component 的样式蓝色,星号(必填)为红色。
随着Hook API我会做这样的事情:
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import MuiFormLabel from '@material-ui/core/FormLabel'
const useStyle = makeStyles({
root: {
color: 'blue'
},
asterisk: {
color: 'red'
},
})
const FormLabel = ({ children }) => {
const classes = useStyle()
return (
<MuiFormLabel
classes={{
root: classes.root,
asterisk: classes.asterisk
}}
>
{children}
</MuiFormLabel>
)
}
我可以使用样式化 API 将 root
和 asterisk
传递给我的组件吗?
我试过了,还是不行
import React from 'react'
import { styled } from '@material-ui/core/styles'
import MuiFormLabel from '@material-ui/core/FormLabel'
const StyledFormLabel = styled(MuiFormLabel)({
'.MuiFormLabel-root': {
color: 'blue'
},
'.MuiFormLabel-asterisk': {
color: 'red'
},
})
const FormLabel = ({ children }) => (
<StyledFormLabel>{children}</StyledFormLabel>
)
最佳答案
下面是正确语法的示例。默认情况下,传递给 styled
的对象中的顶级键被假定为 CSS 属性名称。通过在键的开头添加 &
,它让 styled
知道您正在定义嵌套规则。 .MuiFormLabel-root
是不必要的,因为根级别是默认应用属性的位置(例如下面示例中的 color: "blue"
)。 &
是对根级类的引用,因此 & .MuiFormLabel-asterisk
以 MuiFormLabel-asterisk
类的后代元素为目标。
import React from "react";
import { styled } from "@material-ui/core/styles";
import MuiFormLabel from "@material-ui/core/FormLabel";
const StyledFormLabel = styled(MuiFormLabel)({
color: "blue",
"&.Mui-error": {
color: "purple"
},
"& .MuiFormLabel-asterisk": {
color: "green"
},
"& .MuiFormLabel-asterisk.Mui-error": {
color: "red"
}
});
const FormLabel = ({ children }) => (
<>
<StyledFormLabel required>{children}</StyledFormLabel>
<br />
<StyledFormLabel error required>
{children}
</StyledFormLabel>
</>
);
export default FormLabel;
关于reactjs - 在 Material UI 中使用带有样式 API 的多个 CSS 规则名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65356223/