为什么 React 16 中的 Fragments 比容器 div 更好? [英] Why are Fragments in React 16 better than container divs?

查看:27
本文介绍了为什么 React 16 中的 Fragments 比容器 div 更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 16.2 中,添加了对 Fragments 的改进支持.更多信息可以在 React 的博客文章 这里找到.

我们都熟悉以下代码:

render() {返回 (//无关的 div 元素 :(<div>一些文字.<h2>标题</h2>更多文字.<h2>另一个标题</h2>甚至更多的文字.

);}

是的,我们需要一个容器 div,但这没什么大不了的.

在 React 16.2 中,我们可以这样做以避免周围的容器 div:

render() {返回 (<片段>一些文字.<h2>标题</h2>更多文字.<h2>另一个标题</h2>甚至更多的文字.</片段>);}

在任何一种情况下,我们仍然需要一个容器元素包围内部元素.

我的问题是,为什么使用 Fragment 更可取?它对性能有帮助吗?如果是这样,为什么?希望得到一些见解.

解决方案

  1. 速度更快,内存使用更少(无需创建额外的 DOM 节点).这仅对非常大和/或深的树有真正的好处,但应用程序性能通常会因一千次切割而死亡.这少了一个.
  2. 一些 CSS 机制如 Flexbox 和 CSS Grid 有特殊的父子关系,在中间添加 div 使得在提取逻辑组件时很难保持所需的布局.
  3. DOM 检查器不那么杂乱.:-)

你可以在这个 React issue 中找到一些其他用例的描述:添加片段 API 以允许从渲染返回多个组件

In React 16.2, improved support for Fragments has been added. More information can be found on React's blog post here.

We are all familiar with the following code:

render() {
  return (
    // Extraneous div element :(
    <div>
      Some text.
      <h2>A heading</h2>
      More text.
      <h2>Another heading</h2>
      Even more text.
    </div>
  );
}

Yes, we need a container div, but it's not that big of a deal.

In React 16.2, we can do this to avoid the surrounding container div:

render() {
  return (
    <Fragment>
      Some text.
      <h2>A heading</h2>
      More text.
      <h2>Another heading</h2>
      Even more text.
    </Fragment>
  );
}

In either case, we still need need a container element surround the inner elements.

My question is, why is using a Fragment preferable? Does it help with performance? If so, why? Would love some insight.

解决方案

  1. It’s a tiny bit faster and has less memory usage (no need to create an extra DOM node). This only has a real benefit on very large and/or deep trees, but application performance often suffers from death by a thousand cuts. This is one cut less.
  2. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding divs in the middle makes it hard to keep the desired layout while extracting logical components.
  3. The DOM inspector is less cluttered. :-)

You can find the descriptions of some other use cases in this React issue: Add fragment API to allow returning multiple components from render

这篇关于为什么 React 16 中的 Fragments 比容器 div 更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆