简体   繁体   English

访问子组件的样式属性

[英]accessing the style properties of a child component

How can I access the style properties of the children of a component ? 如何访问组件子级的样式属性?

I am creating a frame component that has to know the width of one of it's children in order to set it's own width value. 我正在创建一个框架组件,该组件必须知道其子项之一的width才能设置其自己的width值。

How can I achieve that ? 我该如何实现?

class Frame extends Component {
    state = {}
    componentDidMount() {
        // how can I access the style properties  of
        // a child element ?
        // I would like to know the width
        // of the first child to make Frame
        // render in a specific way
    }

    render() {
        const {children} = this.props;

        return (
                <div style={{width: value}}> // value calculated against the width
                                            // of children[0]
                    {children}
                </div>
        );
    }
}

The DOM is made up of a component tree. DOM由组件树组成。 An element can have a child: between the open tag and the close tag of an element. 元素可以有一个子元素:在元素的打开标签和关闭标签之间。 Those items within these two tags are the children of that element. 这两个标签中的那些项目是该元素的子级。 Thus, you must use 'props.children' rather that just 'children'. 因此,您必须使用“ props.children”而不是“ children”。 The props in this context will be referring to the parent element which this child belongs to. 在这种情况下,道具将指代该孩子所属的父元素。

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

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