React 学习笔记 —— Fragment
发布日期:2021-05-12 21:18:48 浏览次数:10 分类:精选文章

本文共 1071 字,大约阅读时间需要 3 分钟。

Handling Multiple Roots in React JSX

In React's JSX syntax, it's essential to use a single root tag. To avoid unnecessary extra div tags and hierarchical structures, we can use two main approaches.

Fragment Approach

The Fragment component is designed to be ignored in rendering. It allows embedding multiple root components without adding extra DOM nodes to the tree. Perfect for when you need to #[key] your fragments. If you have loops and dynamic content, specify the key attribute for each fragment is crucial.

Example:

import {Fragment} from 'react';...      test     test

Empty Tag Approach

Using empty tags is another great way to embed multiple root nodes without creating real DOM elements. They don’t accept any attributes since they’re meant purely for embedding HTML.

Example:

...   test   test

The key difference between Empty Tags and Fragments is that Fragments can only accept **key** attribute, which is important when you're dealing with list-like structures. However, Empty Tags have no such limitations and are often used for simple content embedding.

上一篇:React学习笔记——Context
下一篇:React学习笔记——3种常用的hooks

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年05月03日 22时48分34秒