访问父组件中的嵌套大子组件 [英] Access a nested grand child component in a parent component

查看:62
本文介绍了访问父组件中的嵌套大子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问视图"组件中的"GreatGrandChild"组件.

I need to access 'GreatGrandChild' component in the 'View' component.

<View>
  <Child>
    ....
  </Child>
</View>

子组件:

<Child>
  <GrandChild>
      ....      
    </GrandChild>
</Child>

GrandChild组件:

<GrandChild>
  <GreatGrandChild>
    ....
  </GreatGrandChild>
</GrandChild>

GreatGrandChild组件:

<GreatGrandChild ref={(component) => { this.component = component; }}>
  ....
</GreatGrandChild>

如何访问视图"组件中的"GreatGrandChild"组件?我可以使用裁判来访问它吗?在那种情况下,哪种生命周期方法最合适?

How do I access the 'GreatGrandChild' component in the 'View' component? Can I access it using refs? Which lifecycle method would be most appropriate in that case?

推荐答案

您可以使用常规道具传递您的引用-但它必须使用其他名称:

You can use a regular prop to pass your ref - but it must have a different name:

// somewhere in constructor
this.greatGrandChild = React.createRef();

<View>
  <Child greatGrandChildRef={this.greatGrandChild}>
    ....
  </Child>
</View>


<Child>
  <GrandChild greatGrandChildRef={this.props.greatGrandChildRef}>
      ....      
    </GrandChild>
</Child>


<GrandChild>
  <GreatGrandChild greatGrandChildRef={this.props.greatGrandChildRef}>
    ....
  </GreatGrandChild>
</GrandChild>

<GreatGrandChild ref={this.props.greatGrandChildRef}>
  ....
</GreatGrandChild>

这与 styled-components 中的 innerRef 以及它们在React文档中的建议非常相似.

This is very much the same idea of innerRef in styled-components and how they suggest it in React docs.

这篇关于访问父组件中的嵌套大子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆