reactjs - 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 代码演示在这里:
解决方案
您需要使用useLayoutEffect
它来获取布局更改,因为它会在执行所有 DOM 突变后触发。
参考:https ://reactjs.org/docs/hooks-reference.html#uselayouteffect
推荐阅读
- ffmpeg - FFMPEG 复用为私有数据流,读取时可能无法识别
- reactjs - 如何从外部引用组件内部的函数?
- react-native - 更新 React Native Stack Navigator 标头中的徽章
- c# - (统一)有没有办法设置粒子系统中每个粒子的位置?
- google-cloud-platform - 如何将容器部署到多个 GCP 项目并使用 Cloud Run 托管?
- linux - 如何使用 ansible playbook 从收集事实中捕获 IP 地址并使用它输入到下一个任务下的文件
- java - 所以这是我第一次在 Java 中使用 console.log,我无法真正识别我的错误
- spring - 如何使用 webflux 在 Spring Boot WebClient 上添加多个客户端凭据
- android - 保持循环执行直到回调完成
- powershell - 用于检查远程 Windows 机器上是否存在本地管理员帐户的 Power-shell 脚本