首页 > 解决方案 > React 获取组件的高度

问题描述

我需要知道一个React 组件在另一个 React 组件中的高度。我知道可以通过调用来达到元素的高度this.cmref.current.clientHeight。我正在寻找这样的东西:

子组件:

const Comp = () =>{
    return(
        <div>some other stuff here</div>
    )
}
export default Comp

父组件:

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidSomething(){
        const height = this.compref.current.clientHeight;
        //which will be undefined
    }
    render(){
        return(
            <div>
                <Comp ref={this.compref} />
            </div>
        )
    }
}

这可能吗?提前致谢。

标签: javascriptreactjs

解决方案


您需要实际引用子组件的 div 以获得所需的元素,而不是子组件本身。为此,您可以将一个函数传递给孩子,然后孩子将其传递给 div。下面的工作示例:

const Comp = (props) =>{
    return(
        <div ref={props.onRef}>some other stuff here</div>
    )
}

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    
    componentDidMount(){
        const height = this.compref.current.clientHeight;
        //which will be undefined --- No more!
        console.log('height: ', height);
    }
    
    onCompRef = (ref) => {
      this.compref.current = ref;
    }
    
    render(){
        return(
            <div>
                <Comp onRef={this.onCompRef} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id='root' style='width: 100%; height: 100%'>
</div>


推荐阅读