代码之家  ›  专栏  ›  技术社区  ›  L-R

对访问节点维度的React ref当前为空

  •  0
  • L-R  · 技术社区  · 7 年前

    我想用 React.createRef() 访问React中DOM元素的维度。

    我在构造函数中创建

    constructor(props) {
    super(props);
    this.container = React.createRef()
    }
    

    像这样分配

      <div id="container"
      ref={this.container}
      >...children</div>
    

    但是当我从内部注销时 componentDidMount()

    componentDidMount(){
    console.log(this.container);
    }
    

    我懂了 {current: null} 在控制台里。但是如果我扩展这个对象,我可以看到我想要访问的所有东西,比如有值的clientHeight。

    enter image description here

    如何访问这些属性?目前 this.container.current.clientHeight 返回空值。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  0
  •   Raju Choudhary    7 年前

    这是我的示例代码:

    class Badge extends React.Component {
    constructor(props) {
    super(props);
    
    this.textWidth = React.createRef();
    this.state = {
      width: ""
    };
    }
    
     componentDidMount() {
    this.textWidth.current.addEventListener("load", this.getWidth());
    }
    
     getWidth = () => {
    this.setState({
      width: this.textWidth.current.clientWidth + 30
     });
    };
    
    render() {
      return (
      <div
        style={{
          width: this.state.width
         }}
         className="badge"
       >
         <p ref={this.textWidth}>{this.props.children}</p>
       </div>
      );
      }
     }
    
    推荐文章