首页 > 解决方案 > getBoundingClientRect().width 返回 0 使用反应钩子

问题描述

在使用 React hook 开发 Swiper 组件时,我通常使用 getBoundingClientRect().width,但在某些示例中 getBoundingClientRect().width 返回 0。

  useEffect(() => {
    const width = containerWrap.current.getBoundingClientRect().width;
    console.log(containerWrap.current.getBoundingClientRect().width)  // 0
    console.log(document.body.getBoundingClientRect().width);         // 750
    // it works well
    // setTimeout(() => {
    //   console.log(containerWrap.current.getBoundingClientRect().width)  // 750
    // }, 0)
    setSwiperWidth(width);
    if (selectedIndex >= count) {
      active.current = 0;
    }
    setSwipeStyle({...swipeStyle, transform: `translate3d(-${width * (selectedIndex >= count ? 1 : (selectedIndex + 1))}px, 0, 0)`, width: ((count + 2) * width) + 'px'})
    return () => {
      containerWrap.current.remove();
    }
  }, [])

我在 useEffect 函数中使用 setTimeout ,效果很好;

简单的 swiper 代码演示在这里:

简单的 swiper 演示代码

标签: reactjsreact-hooksuse-effect

解决方案


您需要使用useLayoutEffect它来获取布局更改,因为它会在执行所有 DOM 突变后触发。

参考:https ://reactjs.org/docs/hooks-reference.html#uselayouteffect


推荐阅读