React: How to access refs in this.props.children

后端 未结 2 1969
感动是毒
感动是毒 2021-02-08 23:55

I want to call a function of a child component.
Is there a possibility to get refs from this.props.children in React.

var ComponentSection = React.createClas         


        
2条回答
  •  有刺的猬
    2021-02-09 00:08

    Ref in React is a relationship between a component and its owner while what you want is a relationship between an element and its parent. A parent-child relationship is opaque, the parent only receives the child elements on render and never gets access to the resolved components.

    In your case, the ref="specificPanel" establishes a link from the MainComponent to the Panel. If you want to call methods of Panel from ComponentSection, it should own the Panels instead of receiving them as children.

    You could always get creative with React.Children.map and React.createElement (cloning the elements by hand and thus stealing them from the original owner), but this introduces some serious potential pitfalls. A better approach would likely be re-thinking the ownership structure of your component tree.

提交回复
热议问题