首页 > 解决方案 > 从 componentDidMount 导出变量

问题描述

如何从 componentDidMount 导出“x”变量,以便在渲染部分使用它?我正在尝试检查我的 div 的 x 位置。

import React from 'react';

class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.selector = React.createRef();
  }

  componentDidMount = () => {
    var rect = this.selector.current.getBoundingClientRect();
    var x = rect.top;
    console.log(x);
   };

  render() {
    return (
      <div className="icon" ref={this.selector}>
        <p>x: {x} & y:</p>
      </div>
    );
  }
}

export default Icon;

标签: reactjs

解决方案


Why not to use the state?

constructor(props) {
   super(props);
   state = {
      x: null,
   };

   this.selector = React.createRef();
}

then inside lifecycle:

componentDidMount = () => {
   var rect = this.selector.current.getBoundingClientRect();
   this.setState({ x: rect.top });
};

and finally inside render:

<p>x: {this.state.x} & y:</p>

推荐阅读