reactjs - 在 Material UI 中使用带有样式 API 的多个 CSS 规则名称

标签 reactjs material-ui styled-components css-in-js

我正在使用 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 将 rootasterisk 传递给我的组件吗?

我试过了,还是不行

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-asteriskMuiFormLabel-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;

Edit FormLabel styled

关于reactjs - 在 Material UI 中使用带有样式 API 的多个 CSS 规则名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65356223/

相关文章:

reactjs - React useEffect 强制我添加触发无限循环的依赖项

reactjs - 为 `Field` redux 组件构建高阶组件

reactjs - 在react-redux中重新加载页面的正确方法是什么?

javascript - 逐列展开 : Expand row by multiple columns and load different components according to the column clicked

reactjs - Material-UI Outlined 输入标签对齐不正确

css - 生产 css 中的 Material-ui

javascript - 如何使用 ReactDOM Render 渲染 React 组件

css - 带样式的组件样式应该位于组件树中的什么位置?

css - 如何使用 material-ui 和 styled-components 定位按钮库

reactjs - 类型错误扩展不是样式组件中的函数