reactjs - react-spring 等效于 react-pose PoseGroup
问题描述
当列表更改时,React Pose PoseGroup 仅使用 FlipMove 选项为列表元素设置动画
https://codesandbox.io/s/inspiring-herschel-37bvs
如何用 react-spring 做到这一点?
{items.map(item => (
<Item key={item} />
))}
如果删除了一个项目,我想为列表设置动画,并且动画顺利填补了空白
解决方案
在 react-spring 中动画到位置有点困难,因为您必须将位置作为样式进行操作。我喜欢使用基于钩子的动画,所以我将组件转换为函数。解决这个问题的最好方法是 react-spring 中的 useTransition 函数。您可以为它定义、输入和离开样式。并且它将应用于删除或添加的每个数组项。
对于该位置,我首先需要 y 位置作为数据,然后作为属性。所以我将索引映射为 y,并将它作为变量引入到道具中以进行插值。
const [items, setItems] = React.useState([0, 1, 2, 3]);
const transitions = useTransition(
items.map((item, i) => ({ label: item, y: i })),
item => item.label,
{
from: { opacity: 0 },
leave: { opacity: 0 },
enter: ({ y }) => ({ y, opacity: 1 }),
update: ({ y }) => ({ y })
}
);
然后,您可以使用渲染部分中的过渡对象来映射带有样式的项目。这里的诀窍是变换风格。y 现在根据数组顺序更改。我们可以基于它创建一个很好的变换样式来移动项目。
<ul className="sidepanel">
{transitions.map(({ item, props, key }, index) => (
<animated.li
style={{
position: "absolute",
opacity: props.opacity,
transform: props.y.interpolate(
y => `translate3d(0,${y * 40}px,0)`
)
}}
className="item"
data-key={item.label % 5}
key={key}
onClick={() => {
setItems([0, 1, 3]);
}}
/>
))}
</ul>
最后的示例,我添加了一个添加随机播放按钮。https://codesandbox.io/s/react-spring-position-animation-di9rb
推荐阅读
- google-cloud-functions - 谷歌云功能:超过 SocketConnectNonbillable Quota
- android-tv - Android TV - Exoplayer 控件显示在模拟器上但不显示在电视上
- python-3.x - python tkinter / canvas / subplot中的交互式垂直线条绘制
- r - 根据时间范围创建列
- r - 如何使用 R 按行值范围过滤数据帧?
- laravel - Laravel 一对多关系中的奇怪行为
- excel - 如何使用公式锁定单元格?
- python - Pyspark:根据另一列重复附加值到当前行生成一列
- graphql - 如何使用 graphql 和 gatsby 解决内容数据不足的问题?
- kubernetes - 调用 webhook inferenceservice.kfserving-webhook-server.defaulter 失败,kubeflow 中出现 x509 证书错误