过渡不适用于子组件,但在应用于父组件时有效



我正在尝试设置子组件的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,则宽度变化不会被动画化。

由于在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>
);
};

通过CSS,您可以将转换应用于父元素;然后将父元素的溢出设置为隐藏。我认为这应该奏效。

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

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

最新更新