【问题标题】:How to re-animate react-spring animation using hooks on button click?如何使用按钮单击时的钩子重新设置 react-spring 动画?
【发布时间】:2020-03-24 21:03:07
【问题描述】:

以下来自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-效果(或任何其他动画)设置动画,例如当我单击按钮或解决承诺时?

【问题讨论】:

    标签: reactjs animation react-hooks react-spring


    【解决方案1】:

    你基本上可以用useSpring和一个事件来制作两个效果。

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

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

    我创建了一个示例。我想你想要第二种情况。在我的示例中,我通过更改其 key 属性来重新渲染第二个组件。

    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

    我希望这就是你的意思。

    【讨论】:

    • Text2 的示例正是我想要的。你能解释一下为什么它适用于 key={on} 吗?也可以在不创建单独组件的情况下做到这一点吗?
    • 这是一个技巧。我想你知道,如果你在循环中创建反应组件,你必须定义 key 属性。 React 使用它来决定在更改期间更新哪个组件以及删除哪个组件。它也适用于单个组件。如果您更改密钥,它将替换为新密钥。我认为您必须创建一个单独的组件,因为您要重新启动 useSpring 初始化。我不知道更简单的解决方案。
    • 我知道按键是如何工作的,但我不知道您可以将一个按键放在单个组件上。有点遗憾,没有额外的组件就没有解决方案。理想情况下,如果useSpring 为此返回一个回调:const {props, reanimate} =&gt; useSpring(...),那就更好了。但也许这甚至是不可能的。无论如何,你的解决方案已经足够好了。
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多