使用 this.props.children 在 React 中创建合成组件

如果你是React的新人,你可能会在各种教程中看到this.props.children。有时它的目的是不清楚,或者你可能想过,`我可以以不同的方式做到这一点。

button children

基本使用

想象一下,我们需要为我们应用程序中的所有调用按钮构建一个<PrimaryButton/>组件。

 1class PrimaryButton extends React.Component {
 2  render() {
 3    return (
 4      <button onClick={this.props.onClick}>
 5        {this.props.text}
 6      </button>
 7    )
 8  }
 9}
10
11//usage
12<PrimaryButton text="Getting Started" onClick={this.somehandler} />

您的设计团队想添加一个小功能:在开始字之前添加一个图标。

 1//refactor
 2class PrimaryButton extends React.Component {
 3  render() {
 4    return (
 5      <button onClick={this.props.onClick}>
 6        {this.props.icon}{this.props.text}
 7      </button>
 8    )
 9  }
10}
11
12//usage
13<PrimaryButton
14  icon={IconFile}
15  text="Getting Started"
16  onClick={this.somehandler}
17/>

虽然这个解决方案肯定是合理的,但它创造了一个紧密的界面与<PrimaryButton/>,因为你必须明确地了解按钮中的东西,这可能会导致脆弱的组件,当你需要引入新功能时很容易破裂。

 1//refactor
 2class PrimaryButton extends React.Component {
 3  render() {
 4    return (
 5      <!--
 6      <button onClick={this.props.onClick}>
 7        {this.props.icon}{this.props.text}
 8      </button>
 9      -->
10      <button onClick={this.props.onClick}>
11        {this.props.children}
12      </button>
13    )
14  }
15}
16
17//usage
18<PrimaryButton onClick={this.somehandler}>
19  <IconFile/> Getting Started
20</PrimaryButton>

注意<PrimaryButton/>对其内容有多么不感兴趣!您可以将任何有效的HTML标签,图像文件,响应组件...甚至可以扭转文本和图标的顺序!

但这奇怪的this.props.children是什么?

此分類上一篇: 奇怪

当我第一次开始使用React时,拥抱this.props.children的最大阻碍之一是因为它被使用的奇怪方式。围绕其他React组件包装React组件?假设所有这些组件将被暗示地传递给父母?在props中使用保留的名称空间来访问...孩子?超奇怪。

但就像JSX最初是多么奇怪,一旦你练习使用this.props.children更多,并习惯了语法......它将变得像JSX一样不可或缺!识别使用父母和孩子关系的地方将变得更加直观。

<$>[注意]孩子是唯一没有通过属性传递的代码,如 onClick onChange 键或风格,而是在你用 React 组件(考虑到父母组件)包装时被暗示传递的。

alligator component

包装上

在现实世界中,React应用程序将包含这些包装组件的混合物(React 团队将它们称为组件组件,因为您将更复杂的 React 组件从更简单的组件中组成),以及不包装任何 React 组件的组件(见我的第一段代码)。

例如,一些好的候选人可以重塑构成组件:模特,浮动 / 点击的样式,通知零食栏,甲板滑动器等 它真的取决于你的判断,以这种构成风格一样严格或宽松。

👉 在 [Codepen] 上查阅演示文稿(https://codepen.io/alligatorio/pen/gxvdxo?editors=1010)。 注意复杂的功能如何使用各种组成的组件逐步分层。

Published At
Categories with 技术
Tagged with
comments powered by Disqus