Fragment与<>
<Fragment> 通常使用 <></> 代替,它们都允许你在不添加额外节点的情况下将子元素组合。
基本使用
// 使用Fragment
const HelloFragmentFunction: React.FC<IProps> = (props) => {
return (
<Fragment>
...
</Fragment>
);
}
// 使用<>
const HelloFunction: React.FC<IProps> = (props) => {
return <>
...
</>
}
返回单个元素
export const HelloFragmentFunction: React.FC<IProps> = (props) => {
return (
<Fragment>
<h1>使用Fragment</h1>
</Fragment>
);
}
export const HelloFunction: React.FC<IProps> = (props) => {
return <>
<h1>{`使用<></>`}</h1>
</>
}
返回多个元素
使用 Fragment 或简写 <>...</> 将多个元素组合在一起且不会改变 DOM 结构
export const HelloFragmentFunction: React.FC<IProps> = (props) => {
return (
<Fragment>
<h1>使用Fragment</h1>
<p>{props.name}</p>
</Fragment>
);
}
export const HelloFunction: React.FC<IProps> = (props) => {
return <>
<h1>{`使用<></>`}</h1>
<p>{props.name}</p>
</>
}
多个元素分配给变量
和其他元素一样,可以将 Fragment 元素分配给变量,作为 props 传递
export const HelloFragmentFunction: React.FC<IProps> = (props) => {
// 变量
const child = <Fragment>child</Fragment>;
return (
<Fragment>
<h1>使用Fragment</h1>
<p>{props.name}</p>
<Greeting child={child} />
</Fragment>
);
}
export const HelloFunction: React.FC<IProps> = (props) => {
// 变量
const child = <>child</>;
return <>
<h1>{`使用<></>`}</h1>
<p>{props.name}</p>
<Greeting child={child} />
</>
}
const Greeting = (props: { child: React.ReactNode }) => {
return <>
{props.child}
</>
};
嵌套
Fragment 和其他元素一样可以进行嵌套使用
export const HelloFragmentFunction: React.FC<IProps> = (props) => {
return (
<Fragment>
<Fragment></Fragment>
<></>
</Fragment>
);
}
export const HelloFunction: React.FC<IProps> = (props) => {
return <>
<Fragment></Fragment>
<></>
</>
}
列表渲染
渲染列表时不能使用 <></> ,需要显式表示为 Fragment 并且需要为每个元素分配一个 key。
const HelloFragmentFunction: React.FC<IProps> = (props) => {
return (
<Fragment>
{
[1, 2, 3, 4].map(item => (
<Fragment key={item}>
<h3>{`title ${item}`}</h3>
<div>{`description ${item}`}</div>
</Fragment>
))
}
</Fragment>
);
}
友情提示
本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。