简体   繁体   English

从React中的ref回调读取getBoundingClientRect值

[英]Reading getBoundingClientRect values from ref callback in React

I'm trying to extract some getBoundingClientRect() data from a series of div s. 我正在尝试从一系列div提取一些getBoundingClientRect()数据。 There are quite a few moving parts because of the way they're animated. 由于它们的动画制作方式,有很多活动部分。 My problem is that the refCallback essentially returns a series of empty DOMRect objects. 我的问题是refCallback本质上返回了一系列空的DOMRect对象。 You're welcome to peruse the full codesandbox at your leisure: https://codesandbox.io/s/lykqzy41j7 . 欢迎您在闲暇时仔细阅读完整的codeandbox: https ://codesandbox.io/s/lykqzy41j7。 Disregard all the redux logic etc. - the boxes are meant to display numbers as they're being typed. 忽略所有redux逻辑等-框用于在键入数字时显示数字。 That's disabled in this sandbox, though. 但是,此沙箱中已禁用该功能。

class Numbers extends Component {
  refCallback = el => {
    console.log(el.getBoundingClientRect);
  };

  render() {
    return this.props.num.map((curr, idx) => (
      <Grid item xs={2}>
        <Child initialPose="closed">
          <div ref={this.refCallback}>
            <Paper className="child" square elevation={10} variant="display1">
              {this.props.num2[idx] ? (

                <CSSTransition in timeout={300} transitionName="digit">
                  <Typography variant="display1">{num2[idx]}</Typography>
                </CSSTransition>
              ) : 
              null}
            </Paper>
          </div>
        </Child>
      </Grid>
    ));
  }
}

I don't see you calling the getBoundingClientRect method, Also checking top , left value for the boundingRect does return a correct value after invoking the method 我看不到您在调用getBoundingClientRect方法,同时在调用方法之后检查boundingRect的topleft值是否返回正确的值

class Numbers extends Component {
  refCallback = el => {
    console.log(el.getBoundingClientRect());
  };

  render() {
    return this.props.num.map((curr, idx) => (
      <Grid item xs={2}>
        <Child initialPose="closed">
          <div ref={this.refCallback}>
            <Paper className="child" square elevation={10} variant="display1">
              {this.props.num2[idx] ? (

                <CSSTransition in timeout={300} transitionName="digit">
                  <Typography variant="display1">{num2[idx]}</Typography>
                </CSSTransition>
              ) : 
              null}
            </Paper>
          </div>
        </Child>
      </Grid>
    ));
  }
}

Working demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM