在 Material UI 中使用多个 CSS 规则名称和样式化 API

eak*_*akl 2 reactjs material-ui styled-components css-in-js

我正在使用 Material UI,并且想使用多个规则名称和样式化 API来设置组件的样式来设置组件的样式。

假设我想设置FormLabel 组件的样式设置为蓝色,并将星号(必需)设置为红色。

使用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>
  )
}
Run Code Online (Sandbox Code Playgroud)

我可以通过root并且asterisk使用样式化 API

我试过了,但没用

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>
)
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 6

下面是正确语法的示例。默认情况下,传递到的对象中的顶级键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;
Run Code Online (Sandbox Code Playgroud)

编辑 FormLabel 样式