css 过渡在子组件上不起作用,但在应用于父组件时起作用

anauzrmj  于 2022-11-19  发布在  其他
关注(0)|答案(3)|浏览(151)

我尝试将子组件的div宽度设置为动画。我的代码很简单:

export const OuterComponent = () => {
      const sidebarCtx = useContext(SidebarContext);
    
      const style =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white " +
        (sidebarCtx.isOpen ? " w-[400px] " : "");
    
      const InnerComponent = ({ children }) => {
        return (
          <div className={style}> // if I apply style just to this div transition won't work anymore
            {children}
            <a>testing</a>
          </div>
        );
      };
    
      return (
        <div className={style}> // if I apply style here and remove the above style on the InnerComponent transition works OK as normal
          <InnerComponent />
        </div>
      );
    };

正如代码注解中所解释的,问题是如果我直接将style应用于InnerComponent,宽度的变化不会被动画化。

nwlls2ji

nwlls2ji1#

由于您在OuterComponent中定义了InnerComponent,因此会在每次OuterComponent渲染时重新启动它,这可能会扰乱您的动画。
试试这个:

const InnerComponent = ({ children, classNames }) => {
        return (
          <div className={classNames}> // if I apply style just to this div transition won't work anymore
            {children}
            <a>testing</a>
          </div>
        );
      };

export const OuterComponent = () => {
      const sidebarCtx = useContext(SidebarContext);
    
      const classNames =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white " +
        (sidebarCtx.isOpen ? " w-[400px] " : "");
    
    
      return (
        <div className={style}> // if I apply style here and remove the above style on the InnerComponent transition works OK as normal
          <InnerComponent classNames={classNames} />
        </div>
      );
    };
pu82cl6c

pu82cl6c2#

通过CSS,您可以只将过渡应用于父元素;然后将父元素的溢出设置为隐藏。我认为这应该可以工作。

zu0ti5jz

zu0ti5jz3#

我不确定,但是你可以试试这个。

const style =
    `w-[${sidebarCtx.isOpen ? 400 : 100}px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white`.

相关问题