防止滚动条出现在 transform: translate with React-Spring

Prevent Scrollbar Appearing on transform: translate with React-Spring

每当我将 translate() CSS 函数添加到 react-spring useTransition 挂钩 fromleave 属性 时该元素将离开视口,我得到一个 vertical/horizontal 滚动条。

const transitions = useTransition(show, null, {
    from: {
        opacity: 0,
        transform: "translate3d(500px,0px,0px) scale(1)"
    },
    enter: {
        opacity: 1,
        transform: "translate3d(0px,0px,0px) scale(1)"
    },
    leave: {
        opacity: 0,
        transform: "translate3d(0px,-500px,0px) scale(1)"
    },
    config: {
        duration: 3000
    }
});

我知道这是预期的,一般的解决方案是将 overflow: hidden 添加到 body

但我不确定如何在动画播放时执行此操作?因为我不想一直将 overflow: hidden 添加到 body,因为我确实需要访问某些页面中的滚动条,而不是在动画启动时?

这里有一个 CodeSandbox 你自己试试看

如有任何帮助,我们将不胜感激。

您可以将正文的 class 更改为 document.body.classList.add 并删除。例如你可以再添加一个useEffect,像这样:

  useEffect(() => {
    if (show) {
      document.body.classList.add("animation");
    } else {
      document.body.classList.remove("animation");
    }
  }, [show]);

当然你必须定义你的风格 class:

.animation {
  overflow: hidden;
}

请参阅此处的示例。 https://codesandbox.io/s/react-spring-scroll-fj6t8

这只是一个粗略的例子。您可以将 classList.remove 添加到 useEffect 的 return。或者如果你想在动画停止时移除它,你可以尝试将它添加到 useTransition 的 onRest 回调中。