【问题标题】:Animate conditional rendering based on props with react-spring基于 props 的动画条件渲染与 react-spring
【发布时间】:2021-10-06 21:26:55
【问题描述】:

我想用react-spring 为表单中的多个步骤设置动画。这是我目前所拥有的。

import React, { useState} from 'react';
import { animated, useSpring } from 'react-spring';

const AnimatedContainer = animated.div
function MultiStepForm() {
  const [step, setStep] = useState(1);
 
  const style = useSpring({
    to: {opacity: 1},
    from: {opacity: 0},
    config: {
        duration: 200
    }
})
  return (
    <AnimatedContainer style={style}>
      {...conditional rendering based on step state}
    </AnimatedContainer>

  )
}

我多次阅读文档,但仍然无法弄清楚如何做到这一点。我以前使用react-transition group,使用起来非常简单,但是对于这个项目,我必须使用react-spring。如果我现在陷入困境,我将不胜感激。

【问题讨论】:

    标签: reactjs animation react-spring


    【解决方案1】:

    我设法为遇到同样问题的任何人做点什么。我没有使用useSpring,而是使用useTransition。

    const [step, setStep] = useStep(1); 
    
    const transRef = useSpringRef();
    
    useEffect(() => {
        transRef.start();
    }, [step]);
    
    const transitions = useTransition(step, {
        ref: transRef,
        keys: null,
        from: {
            ...transition styles
        },
        enter: { opacity: 1, transform: 'translateX(0px)' },
        leave: {
            ...transition styles
        },
        trail: 300, // this is delay between the leave and enter animation - enter will happen 300ms after leave in this case.
        config: { duration: 150 }
    });
    

    然后像这样渲染组件

    function MultiStepForm() {
      return (
      transitions((props, step) => { // props=transition styles defined in useTransition
        step === 1 && (
            <animated.div style={props}><Step1 /></animated.div> and so on.
            )
      })
    )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 2019-07-11
      • 1970-01-01
      • 2018-07-01
      • 2018-05-30
      • 1970-01-01
      • 2021-08-16
      • 2020-07-18
      相关资源
      最近更新 更多