代码之家  ›  专栏  ›  技术社区  ›  Carl Binalla

componentDidMount()中的高度值错误

  •  0
  • Carl Binalla  · 技术社区  · 6 年前

    console.log() 从这里开始:

    import React from 'react';
    
    export default class FixedTopNavigation extends React.Component {
        constructor(props) {
            super(props);
            this.topNav = React.createRef();
        }
        componentDidMount() {
            console.log(this.topNav.current.offsetHeight);
            console.log(this.topNav.current.clientHeight);
            console.log(this.topNav.current.scrollHeight);
        }
        render() {
            return (
                <nav ref={this.topNav} id="topNav" className="fixed-top navbar navbar-expand-md navbar-light bg-light">
                    <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#sideNav" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>
                    <a className="navbar-brand" href="/">Biometrics</a>
                </nav>
    
            )
        }
    }
    

    所有收益 18岁 而不是 45.13条

    如果 componentDidMount() 不返回正确的值,那么正确获取正确值的方法是什么?

    大多数答案/教程或多或少都使用相同的方式 (除了创建ref的方式) ,这就是为什么我不明白为什么这段代码不起作用。

    1 回复  |  直到 6 年前
        1
  •  0
  •   rrd    6 年前

    有两种方法可以实现这一点。

    componentDidMount() {
      setTimeout(() => {
        console.log(this.topNav.current.clientHeight);
      }, 1);
    }
    

    使用findDOMNode()

    componentDidMount() {
      let compRef = ReactDOM.findDOMNode(this.topNav);
      console.log(this.compRef.clientHeight);
    }