簡體   English   中英

React獲取組件的高度

[英]React get height of component

我需要知道另一個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>
        )
    }
}

這可能嗎? 提前致謝。

您實際上需要引用子組件的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> 

const Comp = React.forwardRef((props, ref) => (
  <div ref={ref}> some other stuff here </div>
));

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidMount(){
        const height = this.compref.clientHeight;
        console.log("hieght", height);
    }
    render(){
        return(
            <div>
                <Comp ref={(el) => this.compref = el} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector("#app"))     

你能這樣嘗試嗎? 希望能幫助到你。 請參考轉發引用https://reactjs.org/docs/forwarding-refs.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM