什么是{this.props.children}以及何时应该使用它? [英] What is {this.props.children} and when you should use it?

查看:797
本文介绍了什么是{this.props.children}以及何时应该使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为React世界的初学者,我想深入了解当我使用 {this.props.children} 时会发生什么情况以及使用相同的情况。它在下面的代码片段中的相关性是什么?

Being a beginner to React world, I want to understand in depth what happens when I use {this.props.children} and what are the situations to use the same. What is the relevance of it in below code snippet?

render() {
  if (this.props.appLoaded) {
    return (
      <div>
        <Header
          appName={this.props.appName}
          currentUser={this.props.currentUser}
        />
        {this.props.children}
      </div>
    );
  }
}


推荐答案


甚至是'孩子'还有什么?

React docs说你可以使用道具.children 代表通用盒子并且不提前知道孩子的组件。对我来说,这并不是很清楚。我肯定对某些人来说,这个定义很有意义,但它并不适合我。

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

我对 this.props的简单解释。子项确实是它用于显示调用组件时开始和结束标记之间包含的内容。

一个简单的例子:

这是一个用于创建组件的无状态函数的示例。再次,因为这是一个函数,没有这个关键字所以只需使用 props.children

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children



const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}




此组件包含< img> 正在接收一些道具,然后显示 {props.children }

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

每当调用此组件时, {props.children} 也将是显示,这只是对组件的开始和结束标签之间的内容的引用。

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.



//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}




而不是使用自动关闭标记调用组件<图片/> 如果你调用它将是完整的开始和结束标签<图片> < / Picture> 然后您可以在它之间放置更多代码。

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

这将解除< Picture> ; 来自其内容的组件,使其更具可重用性。

This de-couples the <Picture> component from its content and makes it more reusable.

参考: React的props.children的快速介绍

这篇关于什么是{this.props.children}以及何时应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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