如何在反应弹簧的使用中反转动画顺序过渡



我想设置从数字1到4的项目的不透明度的动画,但如果项目被移除,我想反向运行(从4到1(。我原以为reverse标志会有所帮助,但它什么都没用:

import React, { useState } from "react";
import { animated, config, useTransition } from "react-spring";
export default function App() {
const items = [1, 2, 3, 4];
const [isToggled, setToggled] = useState(false);
const transitions = useTransition(isToggled ? items : [], item => item, {
config: config.gentle,
unique: true,
trail: 250,
reverse: isToggled ? false : true,
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return (
<div className="App">
<button onClick={() => setToggled(!isToggled)}>Toggle</button>
{transitions.map(({ item, key, props }) => (
<animated.div key={key} style={props}>
Issue #{item}
</animated.div>
))}
</div>
);
}

代码沙盒

reverse方法的问题是它反转了数组中的所有内容。您只需要reverseuseTransition结果中的props属性。

像这样简单的数组修改(在typescript中(:

// utils/animation.ts
// or js just modify the type
import { UseTransitionResult } from 'react-spring';
export function reverseTransition<T, Result extends UseTransitionResult<T, object>>(
arr: Result[],
): Result[] {
const result: Result[] = [];
for (let idx = 0; idx < arr.length; idx++) {
result.push({
...arr[idx],
props: arr[arr.length - 1 - idx].props,
});
}
return result;
}

并像这样传递useTransition钩子的结果:

import React, { useState } from "react";
import { animated, config, useTransition } from "react-spring";
// import above code
import { reverseTransition } from "utils/animation";
export default function App() {
const items = [1, 2, 3, 4];
const [isToggled, setToggled] = useState(false);
const transitions = useTransition(isToggled ? items : [], item => item, {
config: config.gentle,
unique: true,
trail: 250,
reverse: isToggled ? false : true,
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return (
<div className="App">
<button onClick={() => setToggled(!isToggled)}>Toggle</button>
{(isToggled ? transitions : reverseTransition(transitions)).map(({ item, key, props }) => (
<animated.div key={key} style={props}>
Issue #{item}
</animated.div>
))}
</div>
);
}

您将获得具有相同内容的反转动画。我希望它能有所帮助!

Codesandbox

注意:我使用的是React Spring v8,而不是v9(您在Codesandbox中使用的版本(

问候

相关内容

  • 没有找到相关文章

最新更新