尝试使用React Spring做一些SVG动画。它工作正常,但我想从组件内的SVG路径计算一些值。由于现在ref最初返回null,然后使用ref更新,因此我可以获取SVG路径的长度。
但是,如果将所有内容都用if(path.current) { ... }
包裹起来,我会遇到一个错误:
Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.)
那我要怎么使用useSpring直到我拥有设置动画所需的值?
沙盒here
简化的测试代码:
const Squiggle = () => {
const path = useRef(null);
const pathLength = path.current.getTotalLength();
console.log(pathLength); // returns null first, then length
const props = useSpring({
config: { duration: 10000 },
x: 0, from: {x: 1000}, // want to set x to pathLength when it's available
})
return (
<animated.svg
strokeDashoffset={props.x}
>
<path ref={path} d="M1 11.888s75.363-8.751 179-4.916c0 0-111.86 10.72-139.164 23.028 0 0 72.003-7.334 106.835-4.581"/>
</animated.svg>
)
}