使用 React Transition Group v2,我希望能够在文本元素和加载旋转器之间平滑过渡。
没有任何 CSSTransitionGroup
元素,我有以下代码:
{isFetchingEvents ? (
<LoadingSpinner />
) : (
<div>Show More</div>
)}
我最初的、天真的解决方法是使用以下方法:
<CSSTransition
in={isFetchingEvents}
timeout={3000}
classNames="marketGroupFade"
>
<LoadingSpinner />
</CSSTransition>
<CSSTransition
in={!isFetchingEvents}
timeout={3000}
classNames="marketGroupFade"
>
<div>Show More</div>
</CSSTransition>
但这不是一个好的解决方案,因为三元运算符已经消失,并且存在 in
属性的重复以及 classNames
的重复。它确实在两者之间进行转换,但随着每个组件的进出,这种转换很粗糙。
是否有一个简洁的解决方案来在三元运算符中呈现的两个组件之间进行转换?
最佳答案
我想我应该以此作为答案。使用 TransitionGroup
组件。 TransitionGroup
是 react-transition-group
包提供的第三个组件。该问题在 link从您的评论中可以看出,它指的是第一个也是最低级别的组件Transition
。 TransitionGroup
组件与 CSSTransition
或 Transition
结合使用。它处理任何子 CSSTransition
或 Transition
上的 in
属性。当两者之一放置在其中时,将子项上的 in
属性设置为 true
,反之亦然,当子项被删除并且您需要更灵活的时候,您可以使用 function
作为子模式将状态传递给转换并手动设置 in
属性。请参阅下面的示例和 CodePen 了解更多详细信息,您还可以查看文档 here
// 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
Prop 所在位置的项目。虽然我不完全确定每个部分是如何它有效。它将所有子元素包装在一个容器组件中,即使在子元素被卸载后也可以渲染它。这样exit
动画就可以被动画化了。
关于javascript - 在与有状态值相关的两个组件之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50857469/