从React中的ref回调读取getBoundingClientRect值

时间:2018-10-17 06:41:09

标签: javascript reactjs material-ui

我正在尝试从一系列getBoundingClientRect()中提取一些div数据。由于它们的动画制作方式,有很多活动部分。我的问题是refCallback本质上返回了一系列空的DOMRect对象。欢迎您在闲暇时仔细阅读完整的codeandbox:https://codesandbox.io/s/lykqzy41j7。忽略所有redux逻辑等-框用于在键入数字时显示数字。不过,在此沙箱中已禁用该功能。

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>
    ));
  }
}

1 个答案:

答案 0 :(得分:0)

我看不到您在调用getBoundingClientRect方法,还要检查topleft的boundingRect值在调用该方法后确实返回正确的值

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