React react.fragment和<>的使用及区别

React一个常用的模式是组件返回多个元素。Fragment可以为你的子元素分组而不需要在DOM上为它们添加额外的节点。

Fragment 使用

c 复制代码
render() {return (
 <React.Fragment> 
	 <ChildA /> 
	 <ChildB /> 
	 <ChildC /> 
 </React.Fragment> );}

短语法使用

这里有一种短语法可以用来声明Fragment,它看起来就像是空标签:

c 复制代码
class Columns extends React.Component {
	render() {
		return (
			<> 
				<td>Hello</td> 
				<td>World</td> 
			</> 
		); 
	}
}

两者区别

使用<React.Fragment>语法声明的Fragment是可以有key的。一个使用场景是将集合映射到一组Fragment数组。举个例子:创建一个描述列表:

c 复制代码
function Glossary(props) {
  return (
    <dl>
      {props.items.map(item => (
        // 没有`key`,将会触发一个key警告
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </dl>
  );

key是唯一能传递给Fragment的属性。在未来,我们可能会支持其他如事件处理器的属性。

相关推荐
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby3 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing3 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩3 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车3 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思4 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫6 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。7 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星7 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒7 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端