简体   繁体   English

在 Material UI 中使用样式组件应用单选按钮颜色?

[英]Apply radiobutton color using styled-components in Material UI?

In the Material UI documents, they provided sample code to show how one can change the color of a Radiobutton.在 Material UI 文档中,他们提供了示例代码来展示如何更改单选按钮的颜色。

const GreenRadio = withStyles({
  root: {
    color: green[400],
    '&$checked': {
      color: green[600],
    },
  },
  checked: {},
})(props => <Radio color="default" {...props} />);

I would like to replicate this with styled-component instead ie const StyledRadio = styled(Radio) but I am not too familiar with the syntax such as the ampersand and the dollar sign - how can I do this?我想用styled-component复制它,即const StyledRadio = styled(Radio)但我不太熟悉与符号和美元符号等语法 - 我该怎么做?

When using styled components with MUI, the CSS is applied to the root class of the component.当使用带有 MUI 的样式组件时,CSS 将应用于组件的root class。 If you need to apply a more specific style, then you'll need to target the relevant class.如果您需要应用更具体的样式,则需要定位相关的 class。 In this case, you'll need to target the .Mui-checked class:在这种情况下,您需要定位经过.Mui-checked的 class:

const StyledRadio = styled(Radio)`
  color: ${green[400]};
  &.Mui-checked {
    color: ${green[600]};
  }
`;

The MUI docs are really good in that they list the CSS classnames for each component. MUI 文档非常好,因为它们列出了每个组件的 CSS 类名。 If you visit the API docs for the Radio component , you'll see the .Mui-checked class listed there (under the 'Global Styles' column).如果您访问有关 Radio 组件的 API 文档,您将看到那里列出的.Mui-checked class(在“全局样式”列下)。

Here's a working example in Code Sandbox: https://codesandbox.io/embed/styled-components-9pewl这是代码沙箱中的一个工作示例: https://codesandbox.io/embed/styled-components-9pewl

Here's the appropriate styled-components syntax:这是适当的样式组件语法:

const GreenRadio = styled(Radio)`
  color: ${green[400]};
  &.Mui-checked {
    color: ${green[600]};
  }
`;

编辑 Radio 自定义颜色样式组件

Related documentation: https://material-ui.com/customization/components/#pseudo-classes相关文档: https://material-ui.com/customization/components/#pseudo-classes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM