反应过渡组不将 CSS 类应用于目标 div



我使用React转换组、顺风、纯css或任何其他框架都无关紧要。如果我写下面这样的简单组件来显示一些转换,就不会发生转换。在这里,我使用了反应过渡组,但我也测试了其他组,结果是一样的。

export const OuterComponent = () => {
const [show, setShow] = useState(false);
const InnerComponent = () => {
return (
<div>
<CSSTransition 
in={show}
timeout={600}
classNames={"sidebar-transition"}
>
<div className="sidebar"></div>
</CSSTransition>
</div>
);
};
return (
<div>
<InnerComponent />
<button onClick={() => setShow((prev) => !prev)}>click me</button>
</div>
);
};

如果我像下面这样写组件,一切都会正常工作。

export const OuterComponent = () => {
const [show, setShow] = useState(false);
const InnerComponent = ({ children }) => {
return (
<div>
<div className="sidebar">{children}</div>
</div>
);
};
return (
<div>
<CSSTransition
in={show}
timeout={600}
classNames={"sidebar-transition"}
>
<InnerComponent />
</CSSTransition>
</div>
);
};

另一个使用顺风和相同结果的例子:

export const OuterComponent = () => {
const [show, setShow] = useState(false);
const style =
"w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white " +
(show ? " w-[400px] " : "");
const InnerComponent = ({ children }) => {
return (
<div className={style}> // if I apply style just to this div transition won't work anymore
{children}
</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>
);
};

有人能告诉我发生了什么事吗?我几乎尝试了我脑海中的任何解决方案,奇怪的是,我认为一些简单的事情正在发生,但我无法理解

我找到了答案。这里发生的问题是,Innercomponent已经在OuterComponent内部声明,在每次渲染时,它都会被重新初始化,并导致一些异常行为。为了解决这个问题,我只需要将InnerComponent移到OuterComponent的定义之外,这就可以了。

最新更新