Why are Fragments in React 16 better than container divs?

后端 未结 6 1706
陌清茗
陌清茗 2020-12-22 15:39

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 fol

6条回答
  •  温柔的废话
    2020-12-22 16:11

    Adding to all answers above there is one more advantage: code readability, Fragment component supports a syntactic sugar form, <>. Thus the code in your question can be written more easily as:

    render() {
      return (
        <>
          Some text.
          

    A heading

    More text.

    Another heading

    Even more text. ); }

    According to docs,

    In React, this desugars to a element, as in the example from the previous section. (Non-React frameworks that use JSX may compile to something different.)

    Clutter-free, right ?

    Note that you still need to use syntax if you need to provide key to the fragment.

提交回复
热议问题