React JSX - children
目录
1.React children是什么
2.为什么使用
3.怎么使用
React children是什么
children只是简单的传递props到子组件
在我们封装或者开发一个复用组件的时候,我们大多数都会采用props的形式传给复用的组件
<Button color="orange" text="点击" />
但是,考虑下如果我们传的不仅仅只是一些字符串、数组和对象这些数据类型,而是包含的JSX时,代码会变得复杂。
虽然这样看起来可以实现,但是看起来并不干净。这就是children的雏形。
<Post children={
<>
<h1>My first Post</h1>
<p>Some intro text</p>
<p>A paragaph</p>
</>
}/>
为什么使用
如图所示,想象一个场景,你的导航栏和页面底部已经是封装好的。
使用时每次都要重新引入header和Footer,而我们关注的点就只是Post本身,这时候就应该使用children。
<App>
<Header>My first Post</Header>
<Post>Some intro text</Post>
<Footer>A paragaph</Footer>
</App>
怎么使用
以上面那段代码为例子,这样我们就只需要关注<Post />的内容。
function PublicCection({title,children}){
return(
<>
<Header text="My first Post"/>
<p>title</p>
{children}
<Footer text="A paragaph"/>
</>
)}
<App>
<PublicCection title="my second blog">
// children部分 --- start
<section>
<p>content</p>
....
</section>
// children部分 --- end
</PublicCection>
</App>
另外 PublicCection 的标签也可以传递props属性。
结尾
至此关于react的children内容赞告一段落。