试图找出如何使用React Spring设置多个弹簧的位卡住了,然后弹簧将按链序列进行动画处理。
这个想法是获取数组中每个路径的长度,这发生在useEffect
中。提取长度后,我想使用它们来设置单独的弹簧,这些弹簧共同构成SVG箭头的动画。
Here's a hardcoded example可以按预期工作(在视口中单击任意位置,箭头将变为动画)
代码当前看起来像这样(Code Sandbox):
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>
)
}