繁体   English   中英

React + TS:如何获得所有孩子的身高?

[英]React + TS: How to get all children heights?

我正在使用 React 和 Typescript,使用 class 组件。 我的道具类型如下所示:

type Props = {
    children?: React.ReactNodeArray;
}

我的渲染 function 看起来像这样:

render(): JSX.Element {
    return (
        <div>
            {children}
        </div>
    );
}

我知道使用 refs 来获取孩子的身高,但我认为在这种情况下这是不可能的。 如何通过道具获得孩子的身高? 感谢您提供的任何帮助!

我终于解决了这个问题! 这里的关键是不要使用props.children来获取孩子,而是使用ref.current.childNodes代替。 这是一个例子:

constructor() {
    this.container = React.createRef();

...

getHeights() {
    const children = this.container.current.childNodes;
    for (let i = 0; i < children.length; i++)
        console.log((children[i] as any).clientHeight);
}

...

render() {
    return (
        <div ref={this.container}>
            {this.props.children}
        </div>
    );
}

(children[i] as any)部分在使用 Typescript 时是必需的,因此解释器不会抱怨ChildNode没有clientHeight属性。

这是一个 jsfiddle,显示了这个的 SSCCE: JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM