在 React 中添加和删除 类

Add and remove classes in React

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

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"}