我想我把这个作为答案。使用TransitionGroup
组件。TransitionGroup
是react-transition-group
软件包提供的第三个组件。您评论链接中的那个问题是指第一级和最低级组件Transition
。该TransitionGroup
组件与CSSTransition
或结合使用Transition
。它处理in
任何孩子CSSTransition
或Transition
. 当两者之一放置在其中时in
,将子项上的道具设置为true
,反之亦然,当子项被移除时,当您需要更灵活时,您可以使用function
as children 模式将状态传递给转换并手动设置in
支柱。查看以下示例和 CodePen 了解更多详细信息,您还可以查看文档这里
// Create CSSTransition Higher Order Component
const slideHOC = (InputComponent) => {
return props => (
<CSSTransition {...props}>
<InputComponent className="slide" />
</CSSTransition>
);
};
// Create CSSTransition components it can be a list but it doesn't have to be.
const groupItems = [
{
id: uuid.v4(),
element: slideHOC(props => (<h3 {...props}>Hello</h3>))
}, {
id: uuid.v4(),
element: slideHOC(props => (<h3 {...props}>World!</h3>))
},
];
// Reusable CSSTransition props
const transProps = {
appear: true,
timeout: {
enter: 350,
exit: 500,
},
classNames: "slide",
};
// And add this somewhere in your render component
<TransitionGroup
className="test-component-one"
childFactory={child => React.cloneElement(child, transProps)}
>
{groupItems.map(({ id, element: Element }) => {
return (<Element {...transProps} key={id} />)
})}
</TransitionGroup>
// If you want to map an array to can do it like so. Note the key prop on the
// instances of FadeHOC must be set and unique to the CSSTransition for the
// childFactory to work.
FadeHoc = faceHOC(props => (<h3 {...props}>Hello</h3>));
<TransitionGroup
className="test-component-one"
childFactory={child => React.cloneElement(child, transProps)}
>
<FadeHOC {...transProps} key={id} />
<FadeHOC {...transProps} key={id} />
</TransitionGroup>
// Or if you want more flexibility you can do something like this
<TransitionGroup
className="test-component-one"
childFactory={child => React.cloneElement(child, transProps)}
>
{(state) => (
<FadeHOC in={state === 'entered'} {...transProps} key={id} />
<FadeHOC in={state === 'exited'} {...transProps} key={id} />
)}
</TransitionGroup>
CodePen来看看它的实际效果。
TransitionGroup
还能够继续渲染尚未安装在childFactory
道具进入的位置的项目。虽然我不完全确定它的每个部分是如何工作的。它的所有子元素并将它们包装在一个容器组件中,即使在子元素被卸载后也可以渲染它。这样exit
动画就可以动画化了。