如何在单击按钮时使用钩子重新制作 react-spring 动画?

How to re-animate react-spring animation using hooks on button click?

以下来自 official examples 的简单组件:

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和一个事件产生两种效果。

  1. 您可以根据事件的状态更改样式,例如不透明度。

  2. 您可以在状态更改时重新启动动画。最简单的重启方法是重新渲染它。

我创建了一个示例。我想你想要第二种情况。在我的示例中,我通过更改其键 属性.

重新呈现第二个组件
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

我希望这就是你的意思。