【问题标题】:How do I pause the animation in React Spring?如何在 React Spring 中暂停动画?
【发布时间】:2021-07-15 20:26:42
【问题描述】:

我试图在 3 秒后暂停 React Spring 中的动画, 我尝试了以下代码,但没有成功。

                      const pb = props => {
                        const spring = useSpring({
                            from: {
                                progress: 0
                            },
                            to: {
                                progress: 100
                            },
                            pause: _ => {
                            setTimout(() => {
                            return true
                            },3000)
},
                            config: { duration: props.timeout ?? 3000 },
                        });

                        console.log(spring);
                        const style = {
                            width: spring.progress.to(e => `${e}%`), 
                        };
                        return (
                            React.createElement(animated.div, {...props,
                            style: {
                                ...style,
                                ...props.style
                            }
                            })```

【问题讨论】:

    标签: javascript node.js reactjs react-spring


    【解决方案1】:

    在当前版本的 react-spring v9.2 中,你可以使用 useSpring 并传递一个返回 stylesapi 的函数来控制动画状态,使用这个 api 我们可以轻松暂停并恢复动画

    function TestComponent() {
    
      const [pause, setPause] = useState(false);
    
      const [styles, api] = useSpring(() => ({
        from: { opacity: 0 },
        to: { opacity: 1 },
        config: {
          mass: 18.6,
          tension: 7,
          friction: 161
        },
      }))
    
      return (
        <>
          <animated.div style={styles}>
            {'Fade in effect'}
          </animated.div>
    
          <button onClick={() => { api.pause() }}>{'pause'}</button>
          <button onClick={() => { api.resume() }}>{'resume'}</button>
        </>
      );
    
    }
    

    你可以看到结果如何

    如果您想在3 seconds 之后暂停,您可以使用useEffectsetTimeout

    function TextComponentTimeout() {
    
      const [pause, setPause] = useState(false);
    
      const [styles, api] = useSpring(() => ({
        from: { opacity: 0 },
        to: { opacity: 1 },
        config: {
          mass: 18.6,
          tension: 7,
          friction: 161
        },
      }))
    
      useEffect(() => {
        setTimeout(() => {
          api.pause();
        }, 3000);
      }, []);
    
      return (
        <>
          <animated.div style={styles}>
            {'Fade in effect'}
          </animated.div>
    
        </>
      );
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多