如何在 React 中对 className 更改使用转换?

How to use transition on className change in React?

在单击按钮时,我将 class名称 'a' 添加或删除到 div。它变为 50px 宽度但没有过渡

const Navbar = ({ size }) => {
    const MobileNavigation = styled.nav`
        div {
            width: 100px;
            height: 100px;
            background-color: blue;
            transition: width 1s;
            &.a {
                width: 50px;
            }
        }
    `;

    const [active, setActive] = useState(0);

    if (size.width < 500 || (size.width > size.height && size.width < 800)) {
    return (
        <MobileNavigation>
            <button
                onClick={() => {
                    if (active) {
                        setActive(false);
                    } else {
                        setActive(true);
                    }
                }}
            >
                button
           </button>
            <div className={active ? 'a' : ''}></div>
        </MobileNavigation>
}
    );
export default withSize()(Navbar);

如何将 class 添加到带有过渡的元素中?谢谢!

您的样式组件需要移出 NavBar。每次 NavBar 重新渲染时,您都在创建一个全新的 MobileNavigation 组件,而该新组件不知道它应该从之前的 width

过渡
const MobileNavigation = styled.nav`
  div {
    width: 100px;
    height: 100px;
    background-color: blue;
    transition: width 1s;
    &.a {
      width: 50px;
    }
  }
`;

const Navbar = ({ size }) => {
  const [active, setActive] = useState(false);

  if (size.width < 500 || (size.width > size.height && size.width < 800)) {
    return (
      <MobileNavigation>
        <button
          onClick={() => {
            if (active) {
              setActive(prevState => !prevState);
            } else {
              setActive(prevState => !prevState);
            }
          }}
        >
          button
        </button>
        <div className={active ? "a" : ""} />
      </MobileNavigation>
    );
  }

  return null;
};

export default withSize()(Navbar);