this.props.children 的实时用例

Real-Time use case of this.props.children

我已经阅读了很多文章来找出 this.props.children 的实时用例但是我没有找到我正在寻找的答案 for.I 知道 this.props.children 被使用访问数据 b/w 组件的开始和结束标记。但是我的问题是为什么我们不能在组件中添加一个 prop 而不是写入数据 b/w 开始和结束标记。 例如:

<Example>This is data<Example> //can be accessed as this.props.children
can be written as 
<Example data="This is data"/> //can be accessed as this.props.data

有人可以用实时示例向我解释一下我们可以仅使用 this.props.children 来完成特定任务的地方吗?

例如,如果您有复杂的子组件:

<Card>
   <div class='title'>Title</div>
   <div class='content'>Content</div>
</Card>

这会比你这样写更容易:

<Card content={[<div class='title'>Title</div>, <....>]} />

您可以在这里找到相同的内容,例如在 Material-UI here 的抽屉组件中。 Drawer 是一个从左边滑动的组件,它可以包含任何东西,所以使用 props.childrens.

在制作应用程序时,您需要一个父组件来呈现组件中的任何内容。我能想到的用例是:

  1. 当您想根据路线变化打开不同的组件时。

    const App = ({ children }) => (
        <div className="full-height">
            {children}
        </div>
    );
    
  2. 当您想要在整个应用中为通用元素(例如 bodyhead 等)使用相同的样式时。您只需在该组件上应用,例如,在上面的示例中, full-height 将在顶部组件的应用程序中的任何地方应用。 (显然还有其他解决方法,但这总是更清楚)

  3. 对于您想要公开组件的用例(当组件不提前知道子组件时),因为库和道具可能有很大差异并使渲染复杂化。阅读 this

显然您不必使用它,但它使代码更加优雅和易于理解。