ReactJS:为什么要使用 this.props.children? [英] ReactJS: Why use this.props.children?

查看:38
本文介绍了ReactJS:为什么要使用 this.props.children?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到我编写的所有组件都没有使用 {this.props.children}.

I've realised that none of the components I write use {this.props.children}.

我倾向于按照官方文档在顶部的方式编写组件https://facebook.github.io/react/docs/multiple-components.html.

I tend to compose my components the way the official docs state at the top of https://facebook.github.io/react/docs/multiple-components.html.

正在嵌套这样的组件...

Is nesting the components like this...

<A>
  <B />
  <C />
</A>

...像这样编写它们有好处吗?:

...beneficial over composing them like this?:

A.js

render() {
    <B />
    <C />
}

假设这是正确的术语,我错过了什么?

Presuming that's the right terminology, what am I missing?

推荐答案

在我的应用程序中,我很少使用 this.props.children,因为我通常很清楚我想要渲染哪些子级.在库或编写为在特定组件层次结构之外重用的组件中,我经常看到它.我认为 this.props.children 与该用例更相关.

In my applications I rarely use this.props.children, because I often know specifically what children I want to render. In libraries, or components written to be re-used outside of a specific component hierarchy, I've seen it often. I think this.props.children has more relevance to that use-case.

我想我会详细说明 this.props.children 可以派上用场的一些情况.一个这样的例子是在创建遵循render prop"模式的组件时.即我有一些组件需要从多个渲染道具"HoC 中提取数据,例如 Apollo Query 组件以及状态管理 HoC.我将所有不同的数据源组合到一个 HoC 中,然后将 children 作为函数调用,传入提取我需要的所有数据的结果.话虽如此,这些天我更喜欢并期待更广泛地采用 Hooks 作为替代方案渲染道具.

I thought I'd elaborate on some cases that this.props.children can come in handy. One such example is when creating components which follow the 'render prop' pattern. i.e. I've got some components that require pulling data in from multiple 'render prop' HoC's, such as an Apollo Query component as well as a state management HoC. I combined all my different data sources into one HoC and then called children as a function, passing in the result of pulling out all the data I needed. That being said these days I prefer and look forward to wider adoption of Hooks as an alternative to render props.

真的是任何你想要渲染任意子组件的组件;我使用过的另一个例子 props.children 是在创建一个要求用户在呈现孩子之前进行身份验证的 HoC 时,当用户未登录时重定向到登录屏幕.我可以包装我的任何受保护"屏幕组件使用此身份验证 HoC.

Really any component which you want to render arbitrary children; another example I've used props.children is when creating a HoC that required a user be authenticated before rendering the child, redirecting to a login screen when the user isn't logged in. I could wrap any of my 'protected' screen components with this auth HoC.

我的大多数组件仍然不使用它,但只是在情况需要时应用的另一种工具.

It's still something the majority of my components don't use, but just another tool to be applied when the situation warrants.

这篇关于ReactJS:为什么要使用 this.props.children?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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