首页 > 解决方案 > 在 React 中添加和删除类

问题描述

如何在单击时添加/删除类名以更改某些组件的样式?

在此处输入图像描述

标签: cssreactjsmaterial-uimakestyles

解决方案


const [isRotated, setIsRotated] = useState(false);

handleClick() {
 setIsRotated(true)
}

<button className={isRotated && 'rotate-class'} onClick={handleClick} />
{ !isRotated && <Element/>} // this will hide the element when clicked on the button

这将是一种比设置display: none其他元素更好的方法,但如果您必须这样做,请执行以下操作:

 <Element style={{ display: isRotated ? 'none': 'block' }} /> // I'm guessing the default style of display is 'block' of the elements you want to hide

推荐阅读