【问题标题】:Reactjs slide animation problem without unknown target dimensions没有未知目标尺寸的Reactjs幻灯片动画问题
【发布时间】:2021-10-27 23:39:02
【问题描述】:

在我的 react 应用程序中,我正在制作一些动画以使其更好。我想通过从上方滑动来使 div 出现,然后通过向后滑动来消失。

我在堆栈中使用bootstrap 5.1.0react-bootstrap 1.6.1

我想出了一个解决方案,将内容包装在一个 div 中,并根据需要在 window.innerHeight0 之间切换其 maxHeight。我还添加了一个自定义 css 类

.transition-height{
    transition: max-height 0.5s ease-in-out;
}

问题很明显,当我关闭 div 时,动画从一个非常高的 maxHeight 值开始,因此在关闭触发事件和您看到 div 实际关闭的那一刻之间存在延迟。我使用了window.innerHeight,因为我没有已知的高度目标值可以使用,这取决于 div 内容的长度。

我将代码上传到codesandbox,所以你可以看到它的行为。

如何避免这种情况?

【问题讨论】:

  • 你能不能只转换到高度 0 并且过渡在收缩阶段的高度上?

标签: css reactjs twitter-bootstrap css-animations


【解决方案1】:

在您的情况下,只需要使用 useRef 获取 div 的高度,show = true 何时设置当前高度。 codesandbox exapmle

ApperDiv

const AppearDiv = (props) => {
  let { show = false, className = "", style = {} } = props;
  const ref = useRef(null);
  const getPaperBoxHeight = ref.current?.scrollHeight || 0;

  const filteredProps = Object.entries(props)
    .filter(([k, _]) => !["className", "show", "style"].includes(k))
    .reduce((p, [k, v]) => ({ ...p, [k]: v }), {});

  style = show ? { height: getPaperBoxHeight } : { height: 0 };
  return (
    <div
      ref={ref}
      className={
        "overflow-hidden transition-height" + (className && ` ${className}`)
      }
      style={style}
      {...filteredProps}
    />
  );
};

【讨论】:

  • scrollHeight 正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2014-01-03
  • 2018-06-02
  • 1970-01-01
相关资源
最近更新 更多