通常使用 <>…</> 代替,它们都允许你在不添加额外节点的情况下将子元素组合。相当于vue的内置标签<template/>
1. 返回多个元素
<><OneChild /><AnotherChild />
</>
2. 分配多个元素给一个变量
和其他元素一样,你可以将 Fragment 元素分配给变量,作为 props 传递。
function CloseDialog() {const buttons = (<><OKButton /><CancelButton /></>);return (<AlertDialog buttons={buttons}>Are you sure you want to leave this page?</AlertDialog>);
}
3. 组合文本与组件
可以使用 Fragment 将文本与组件组合在一起。
function DateRangePicker({ start, end }) {return (<>From<DatePicker date={start} />to<DatePicker date={end} /></>);
}
4. 渲染 Fragment 列表
需要为每一个元素分配一个 key时,需要显式地表示为 Fragment,而不是使用简写语法 <></>
function Blog() {return posts.map(post =><Fragment key={post.id}><PostTitle title={post.title} /><PostBody body={post.body} /></Fragment>);
}