有点卡住试图弄清楚如何使用React Spring设置多个弹簧,然后弹簧将按链顺序进行动画处理。
这个想法是获取数组中每个路径的长度,这发生在useEffect
. 当获取长度时,我想使用它们来设置单独的弹簧,这些弹簧共同构成 SVG 箭头的动画。
这是一个按预期工作的硬编码示例(单击视口中的任意位置,箭头将动画)
代码目前看起来像这样(代码沙箱):
const arrowData = {
stroke: 'red',
viewBox: '0 0 278 549',
paths: [
'M204.974 2.775c57.056 87.536 81.796 175.997 58.823 266.51C223.401 428.443-11.634 400.007 6.5 312.033 24.638 224.062 190 252 190 356c0 69.333-8 128.617-24 177.852',
'M223.324 500.772l-60.288 39.978-26.437-68.621',
]
};
const Arrow = () => {
const [draw, setDraw] = useState(false);
const [pathLengths, setPathLengths] = useState([]);
// path refs
const pathsRef = useRef(arrowData.paths.map(() => createRef()));
// spring animation refs for chaining
const springsRef = useRef(arrowData.paths.map(() => createRef()));
useEffect(() => {
const calculatedPathLengths = pathsRef.current.map(
ref => ref.current.getTotalLength()
);
setPathLengths(calculatedPathLengths);
// dynamically setup multiple springs for chained animation here, but how?
}, [setPathLengths]);
return (
<div style={{pointerEvents: 'auto'}} onClick={() => setDraw(draw => !draw)}>
<svg
viewBox={arrowData.viewBox}
stroke={arrowData.stroke}
fill="none"
strokeWidth="10"
>
{arrowData.paths.map((path, index) => (
<animated.path
key={index}
ref={pathsRef.current[index]}
strokeDasharray={pathLengths[index]}
strokeDashoffset="0" // <- value to be animated
d={path}
/>
))}
</svg>
</div>
)
}