在React中,当你需要在组件的根元素下渲染多个子节点时,但又不想引入额外的DOM元素作为容器,你可以使用Fragment。Fragment允许你将一组子节点组合在一起而不添加额外节点到DOM中。
下面是一个使用Fragment的例子:
import React,{PureComponent,Fragment} from "react";
export class App extends PureComponent {
constructor(){
super()
this.state = {
sections:[
{title:"哈哈哈",content:"我是内容,哈哈哈"},
{title:"呵呵呵",content:"我是内容,呵呵呵"},
{title:"嘿嘿嘿",content:"我是内容,嘿嘿嘿"},
{title:"嘻嘻嘻",content:"我是内容,嘻嘻嘻"},
]
}
}
render(){
const { sections } = this.state
return (
<>
<h2>我是App的标题</h2>
<p>我是App的内容,哈哈哈</p>
<hr />
{
sections.map(item=>{
return (
<Fragment key={item.title}>
<h2>{item.title}</h2>
<p>{item.content}</p>
</Fragment>
)
})
}
</>
)
}
}
export default App
在上面的例子中,<></>
是Fragment的简写形式。你也可以使用React.Fragment
来达到同样的效果:
import React,{PureComponent,Fragment} from "react";
export class App extends PureComponent {
constructor(){
super();
this.state = {
}
}
render(){
return (
<React.Fragment>
{/* 这里是你的子节点 */}
</React.Fragment>
)
}
}
在React中,Fragment是一个特殊的组件,它没有对应的DOM元素。它只是用来将多个子节点组合在一起,而不会添加额外的DOM元素到DOM树中。最后我们附上浏览器上的效果图:
感谢大家观看,我们下次见!
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我