简体   繁体   English

如何将 `this` 的引用传递给使用功能组件的孩子?

[英]How can I pass a reference of `this` to children using functional components?

I'm working to convert some class based code over to functional (and learning functional react along the way).我正在努力将一些基于 class 的代码转换为函数式代码(并在此过程中学习函数式反应)。

I know that I can pass references to individual variables of a component function as props to children, but is there a <Child parentPage={this} /> equivalent when using functional components?我知道我可以将对组件 function 的各个变量的引用作为道具传递给孩子,但是在使用功能组件时是否有等效的<Child parentPage={this} />

The idea being that then a child component could call this.props.parentPage.updateValue() , instead of needing to do this.props.updateValue() .这个想法是子组件可以调用this.props.parentPage.updateValue() ,而不是需要执行this.props.updateValue() I realize that's actually more work in a simple parent -> child relationship, but when you find yourself a few generations deep, with siblings and cousins all needing to access this.props.parentPage.* .我意识到在简单的父-> 子关系中实际上需要做更多的工作,但是当您发现自己几代人深入时,兄弟姐妹和堂兄弟姐妹都需要访问this.props.parentPage.*

Sounds like you want to avoid prop drilling.听起来您想避免螺旋桨钻孔。 Without knowing the details of your code, it's hard to say what the best solution would be, but most likely you coulduse context for this .在不知道代码细节的情况下,很难说出最好的解决方案是什么,但很可能您可以为此使用上下文

Other than that, you could extract components and pass JSX as children to them .除此之外,您可以提取组件并将 JSX 作为子组件传递给它们 Or just keep passing the props, sometimes that's fine.或者只是不断地传递道具,有时这样也很好。

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

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