首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >反应得到元件尺寸

反应得到元件尺寸
EN

Stack Overflow用户
提问于 2017-10-05 17:54:18
回答 2查看 805关注 0票数 2

我的getBoundingClientRect总是返回一个包含0值的对象。我想是和异步有关吧?下面是获取组件宽度和x的函数的定义。

代码语言:javascript
代码运行次数:0
运行
复制
     componentDidMount () {
         this.setState({ 
            left: Math.round(this.container.getBoundingClientRect().width),                       
           x: Math.round(this.container.getBoundingClientRect().x)                               
        });                                                                                       
  }

以下是呈现函数的开始:

代码语言:javascript
代码运行次数:0
运行
复制
render() {
        const containerStyle = {
             left : `-${Math.min(this.state.left, this.state.x) - 35}px`,                                                 
        };
        return ( !!this.state.visible && 
             <div
                 className={styles.container}
                 style={containerStyle}                                                            
                 ref={(element) => { this.container = element; }}                                  
            >

以下是来自getBoundingClientRect的响应

代码语言:javascript
代码运行次数:0
运行
复制
DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …}
bottom : 0
height : 0
left : 0 
right : 0
top : 0
width : 0
x : 0
y : 0
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-05 18:54:46

试一试

代码语言:javascript
代码运行次数:0
运行
复制
componentDidMount () {
  window.requestAnimationFrame(() => {
    this.setState({ 
      left: Math.round(this.container.getBoundingClientRect().width),                       
      x: Math.round(this.container.getBoundingClientRect().x)                               
    });
  }                                                                                       
}

DOM实际上是可用的,componentDidMount正在调用,这有一些微妙之处;使用requestAnimationFrame将确保它在油漆发生后被调用。

票数 1
EN

Stack Overflow用户

发布于 2017-10-05 18:31:35

您需要使用ref回调,而不是内联ref。当您使用内联ref时,第一个呈现传递该ref将为空。当传入回调时,它只在元素加载后触发。

代码语言:javascript
代码运行次数:0
运行
复制
applyRef(ref) {
    this.container = ref;
}
...
<div
    className={styles.container}
    style={containerStyle}
    ref={this.applyRef}
>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46591978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档