如何在单击时添加/删除类名以更改某些组件的样式?
display: none;
当我点击它和它旁边的所有组件时,我想旋转右边的箭头。我还想在遇到移动断点时添加做同样的事情
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
您可以添加布尔状态和函数以更改状态与此代码相同。
function App() {
const [state, setState] = useState(true);
const rotateHandler = () => {
setState(() => !state);
};
return (
<div className="App">
{/* button for change state */}
<button onClick={rotateHandler}>click for rotate and hide</button>
{/* icon for rotate */}
<div>
<FontAwesomeIcon
icon={faAngleRight}
style={{
transform: state ? "rotate(90deg)" : "rotate(0deg)"
}}
/>
</div>
{/* text hide when */}
<div style={{ display: state ? " block" : "none" }}>
<div>text hide after state is false</div>
<div>you can click on button</div>
<div>for rotate arrow icon</div>
<div>and hide this text</div>
</div>
</div>
);
}
我以内联样式添加条件,但您可以在 className 上添加条件
className={state ? "show" : "hide"}