如何使用单击按钮上的钩子重新动画反应弹簧动画?

时间:2019-11-29 09:10:21

标签: reactjs animation react-hooks react-spring

下面是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效果(或任何其他动画)的动画?

1 个答案:

答案 0 :(得分:1)

您基本上可以通过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

我希望这就是你的意思。