React如何获取props.chidren组件的宽度和高度?

时间:2019-11-14 14:30:19

标签: javascript css reactjs dom

我想创建npm模块进行反应。在此模块中,我需要知道作为props.children传入我的组件的组件的高度和宽度。我无法控制那些孩子。目前我这样做  {React.cloneElement(this.props.children, { ref: this.myRef })} 在render中,然后在其他函数中,我可以通过这种方式获得宽度和高度

let myRect = this.myRef.current.getBoundingClientRect();
if (!this.state.childSize.height && myRect.height !== 0) {
    var cSize = { height: myRect.height, width: myRect.width };
}

但仅当孩子像dom元素一样通过时才有效

<MyModuleComponent>
    <div>Hello world!</div>
</MyModuleComponent>

并且如果将子级作为反应组件传递则无效

<MyModuleComponent>
    <SomeChildComponent/>
</MyModuleComponent>

在这种情况下,this.myRef.current没有getBoundingClientRect函数。

在这种情况下如何获得孩子的身高和身高?

0 个答案:

没有答案