是否可以在 react-spring 中将动画设置为 100%?

Is it possible to animate to 100% in react-spring?

我正在使用 react-spring 尝试在 AJAX 内容加载时制作动画。

我有一个容器组件,有时我想从 0 动画到 'auto',有时我想根据传入的道具动画到 100%。

我设置了一个 const,然后将其传递到 Transition 组件中的 calculatedHeight 属性。然后我使用它来设置已安装子组件样式 属性 中的高度 属性。

const Container = ({ data, children, stretchHeight }) => {
  const loaded = data.loadStatus === 'LOADED';
  const loading = data.loadStatus === 'LOADING';

  const animationHeight = stretchHeight ? '100%' : 'auto';

  return (
    <div
      className={classnames({
        'data-container': true,
        'is-loading': loading,
        'is-loaded': loaded,
        'stretch-height': stretchHeight
      })}
      aria-live="polite"
    >
      {loading &&
        <div style={styles} className='data-container__spinner-wrapper'>
          <LoadingSpinner />
        </div>
      }

      <Transition
        from={{ opacity: 0, calculatedHeight: 0 }}
        enter={{ opacity: 1, calculatedHeight: animationHeight }}
        leave={{ opacity: 0, calculatedHeight: 0 }}
        config={config.slow}
      >
        {loaded && (styles => {
          return (
            <div style={{ opacity: styles.opacity, height: styles.calculatedHeight }}>
              {children}
            </div>
          )
        }
        )}
      </Transition>
    </div>
  )
}

问题是这会导致最大调用堆栈超出错误,因为我认为 react-spring 无法理解“100%”字符串值,只能理解 'auto'.

有解决办法吗?

问题是你切换类型,你从 0 到自动再到 0%。它可以插入自动,但它被插入为一个数字,你会通过将该数字与百分比混合来混淆它。

PS。也许你可以使用 css 来耍点小花招:https://codesandbox.io/embed/xolnko178q

感谢@hpalu 帮助我了解问题所在:

The problem is that you switch types, you go from 0 to auto to 0%. It can interpolate auto, but that gets interpolated as a number, you're going to confuse it by mixing that number with a percentage.

为了解决这个问题,我为开始 结束点创建了常量。

  const containerHeightAnimationStart = stretchHeight ? '0%' : 0;
  const containerHeightAnimationEnd = stretchHeight ? '100%' : 'auto';

然后我在动画中使用了这些:

<Transition
  native
  from={{ opacity: 0, height: containerHeightAnimationStart }}
  enter={{ opacity: 1, height: containerHeightAnimationEnd }}
  leave={{ opacity: 0, height: containerHeightAnimationStart }}
>
  {loaded && (styles => {
    return (
      <animated.div style={styles}>
        {children}
      </animated.div>
    )
  }
  )}
</Transition>

从 & 到需要相同的单位(数字或字符串)

const [percentage, setPercentage] = useState(100);

// wrong
const animationState2 = useSpring({
    from:{width: 0},
    to: {width: `${percentage}%`}
});

// right
const animationState2 = useSpring({
    from:{width: '0%'},
    to: {width: `${percentage}%`}
});