官术网_书友最值得收藏!

Root

One important difference with HTML worth mentioning is that, since JSX elements get translated into JavaScript functions, and you cannot return two functions in JavaScript, whenever you have multiple elements at the same level you are forced to wrap them into a parent.

Let's look at a simple example:

  <div />
<div />

This gives us the following error:

  Adjacent JSX elements must be wrapped in an enclosing tag.

On the other hand, the following works:

  <div> 
<div />
<div />
</div>

Before, React forced you to return an element wrapped with a <div> element or any other tag; since React 16.2.0, it is possible to return an array or string directly:

  // Example 1: Returning an array of elements. 
render() {
// Now you don't need to wrap list items in an extra element
return [
<li key="1">First item</li>,
<li key="2">Second item</li>,
<li key="3">Third item</li>
];
}

// Example 2: Returning a string
render() {
return 'Hello World!';
}

Also, React now has a new feature called Fragment that also works as a special wrapper for elements. It can be specified with empty tags (<></>) or directly using React.Fragment:

  // Example 1: Using empty tags <></> 
render() {
return (
<>
<ComponentA />
<ComponentB />
<ComponentC />
</>
);
}

// Example 2: Using React.Fragment
render() {
return (
<React.Fragment>
<h1>An h1 heading</h1>
Some text here.
<h2>An h2 heading</h2>
More text here.
Even more text here.
</React.Fragment>
);
}

// Example 3: Importing Fragment
import React, { Fragment } from 'react';

render() {
return (
<Fragment>
<h1>An h1 heading</h1>
Some text here.
<h2>An h2 heading</h2>
More text here.
Even more text here.
</Fragment>
);
}
主站蜘蛛池模板: 彰武县| 丰城市| 北安市| 日照市| 永靖县| 平湖市| 湖北省| 遵义市| 洛南县| 盐边县| 无为县| 昆山市| 苏尼特右旗| 镇平县| 息烽县| 翁源县| 五指山市| 宁国市| 永德县| 朝阳县| 吉隆县| 正阳县| 元氏县| 洛扎县| 驻马店市| 武川县| 昂仁县| 大兴区| 乐清市| 驻马店市| 忻州市| 彝良县| 定边县| 牡丹江市| 筠连县| 惠水县| 墨竹工卡县| 辉县市| 榆林市| 汉沽区| 仙游县|