在挂载组件时添加 css class

Adding css class when component will mount

Modal 打开时,我将一些 class 添加到 body 元素

const Modal = ({ ... }) => {
    ...
    useEffect(() => {
        document.body.classList.add('modal-open')
        return () => document.body.classList.remove('modal-open')
    }, [])

但是我注意到在应用 modal-open class 时会有一个快速而短暂的延迟(尤其是当这个 class 包含一些样式如 margin-right: 17pxoverflow-y: hiddenposition: sticky !important) 所以我看到 body 元素在移动,这当然不是一个好的用户体验。

所以我从 useEffect

中添加了 class
document.body.classList.add('modal-open')
useEffect(() => { ... }, [])

它正在运行,但是这行代码 document.body.classList.add('modal-open') 在每次重新渲染时都会执行,而不是在 useEffect

中执行一次

那么有更好的方法吗?也许 componentWillMount 在钩子中等效,因为我没有触及我只是操纵 dom 元素的状态 classes ?

可以使用

useLayoutEffect 代替 useEffect 来更早地应用更改。

The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.