以下来自官方示例的简单组件:
import {useSpring, animated} from 'react-spring'
function App() {
const props = useSpring({opacity: 1, from: {opacity: 0}})
return <animated.div style={props}>I will fade in</animated.div>
}
问题
如何再次为
fadeIn
效果(或任何其他动画)设置动画,例如当我单击按钮或解决承诺时?
你基本上可以使用 useSpring 和一个事件来实现两种效果。
您可以根据事件的状态更改样式,例如不透明度。
您可以在状态更改时重新启动动画。重启最简单的方法就是重新渲染。
我创建了一个例子。我想你想要第二种情况。在我的示例中,我通过更改其关键属性来重新渲染第二个组件。
const Text1 = ({ on }) => {
const props = useSpring({ opacity: on ? 1 : 0, from: { opacity: 0 } });
return <animated.div style={props}>I will fade on and off</animated.div>;
};
const Text2 = () => {
const props = useSpring({ opacity: 1, from: { opacity: 0 } });
return <animated.div style={props}>I will restart animation</animated.div>;
};
function App() {
const [on, set] = React.useState(true);
return (
<div className="App">
<Text1 on={on} />
<Text2 key={on} />
<button onClick={() => set(!on)}>{on ? "On" : "Off"}</button>
</div>
);
}
这是工作示例:https://codesandbox.io/s/upbeat-kilby-ez7jy
我希望这就是你的意思。
理想的方法是使用“命令式 API”来控制动画并避免使用
States
- 因为使用状态每次都会重新渲染组件(可以使用命令式 API 来避免)。
根据他们的文档
...使用从 useSpring 钩子返回的 api 对象,或者通过 useSpringRef 生成并传递给钩子的 api 对象,意味着动画运行时您的组件不会重新渲染。
下面是您应该使用的代码 - 取自文档中链接的sandbox
const ApiComponent = () => {
const api = useSpringRef()
const springs = useSpring({
ref: api,
from: { x: 0 },
})
const handleClick = () => {
api.start({
to: {
x: springs.x.get() === 100 ? 0 : 100,
},
})
}
return (
<div className="flex-container">
<animated.div
onClick={handleClick}
style={{
width: 80,
height: 80,
background: '#ff6d6d',
borderRadius: 8,
...springs,
}}
/>
<span>Render ID – {Math.random()}</span>
</div>
)
}