Nested class in another selected class with makeStyles

强颜欢笑 提交于 2020-06-17 02:56:15

问题


I need to know how to target 'element' when root is selected

This is makeStyles:

const useStyles = makeStyles(theme => ({
   root:{
      '&.selected': {
      }
   },
   element: {
   }
})

This is jsx

<div className={`${classes.root} ${elementSelected ? 'selected : ''}`}>
  <div className={classes.element}>
  </div>
</div>

回答1:


You can use https://www.npmjs.com/package/classnames to achieve this.

const useStyles = makeStyles(theme => ({
   root:{
      '&.selected $element': {
      }
   }
})

And your JSX

import classNames from 'classnames';

...

<div className={classNames(classes.root, elementSelected ? 'selected : '')}>
  <div className={classes.element}>
  </div>
</div>



回答2:


This answer is as an alternative to @Chris' answer.

You don't need to include another package to your project, as you can use 'clsx' from Material-UI. Here's how:

const useStyles = makeStyles(theme => ({
    root:{
        '&.selected $element': {
        }
    }
})

The clsx package comes with Material-UI when you install it.

import clsx from 'clsx';
const classes = useStyles(props);

...

<div className={clsx(classes.root, {
        [classes.selected]: elementSelected
    })}
>
    <div className={classes.element}>
    </div>
</div>


来源:https://stackoverflow.com/questions/59383971/nested-class-in-another-selected-class-with-makestyles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!