如何使用react spring为SVG线的x1坐标设置动画



我正试图用react spring为SVG线的x1坐标设置动画,但什么也没发生。我也没有看到任何错误或失败记录。如何设置反作用弹簧中直线位置的动画?

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
function App() {
const [toggle, setToggle] = useState(false);
const spring = useSpring({
from: { x1: 5 },
to: { x1: 22 }
});
return (
<>
<div>
<button
type="button"
onClick={() => {
setToggle(!toggle);
}}
>
Toggle animation
</button>
</div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="40"
height="40"
viewBox="0 0 40 40"
stroke="#000"
strokeWidth="2"
>
<animated.line
x1="5"
y1="10"
x2="35"
y2="10"
transform="rotate(0 23.5 10)"
styles={spring}
/>
</svg>
</>
);
}
export default App;

我找到了一种方法——这对我来说并不明显,也许它也会帮助其他人:

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
function App() {
const [toggle, setToggle] = useState(false);
const { x1 } = useSpring({
from: { x1: 5 },
to: { x1: 22 },
immediate: toggle === false,
reset: true
});
return (
<>
<div>
<button
type="button"
onClick={() => {
setToggle(!toggle);
}}
>
Toggle animation
</button>
</div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="40"
height="40"
viewBox="0 0 40 40"
stroke="#000"
strokeWidth="2"
>
<animated.line
x1={x1}
y1="10"
x2="35"
y2="10"
transform="rotate(0 23.5 10)"
/>
</svg>
</>
);
}
export default App;

可以将useSpring创建的SpringValue直接分配给SVG属性,这样就可以工作了。特别适用于那些道具,这些道具不能像罗伯特·朗森在原帖中评论的那样风格化。谢谢你指出这一点。

相关内容

最新更新