首页 > 解决方案 > 使用材质 ui 中的 withStyle HOC 的 CSS 选择器

问题描述

我将 material-ui 与 Reactjs 一起使用,对于我选择使用 withStyles HOC 来设置组件样式的样式,问题是我不知道如何将复杂的选择器从 CSS 转换为 React Style,

const Styles ={
  label :{
      width:"100%"
  },

  cardInputRadio:{
      display:"none",
      '&:checked + .cardInput': {
        color: 'green',
        display:"block"
     }
  },

  cardInput:{
      margin:"10px",
    '&:hover': {
        cursor: 'pointer',

     },
    'cardInputRadio:checked+ &':{
        color:'red',
     }

  },
  container:{
      flexGrow:1,
  },
  card: {
    minWidth: 100,
    width:300,
    display:"inline-block"
  },

     title: {
      fontSize: 14,
     },

   } ;

这就是我现在正在做的,当然我正在使用

export default withStyles(Styles)(MyComponent);

如您所见,我正在尝试翻译此 css 以响应样式

.card-input-element:checked + .card-input {
     box-shadow: 0 0 1px 1px #2e0071;
 }

我想在选中单选按钮时更改卡片颜色,但我无法使用 Material UI 样式 HOC 谢谢

标签: cssreactjsmaterial-ui

解决方案


添加条件样式的一种方法是使用类名库。

假设您的组件具有“已检查”道具,则您的样式将遵循

cardInputRadio:{
  display:"none"
},
cardInputRadioChecked: {
  color: 'green',
  display: 'block'
}

在你的组件中,你定义你的 classNames 像这样

import classNames from 'classnames'

const MyInputRadioComponent ...
  const { checked } = props
  const classNames = classNames({
    [styles.cardInputRadio]: true,
    [styles.cardInputRadioChecked]: checked
  })

  return <YourRadioComponent classNames={classNames}/>

推荐阅读