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

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>
);
}
主站蜘蛛池模板: 普安县| 沛县| 永善县| 尖扎县| 同仁县| 博爱县| 高淳县| 周至县| 光山县| 新竹县| 全州县| 额济纳旗| 开阳县| 五峰| 齐河县| 望都县| 鄱阳县| 阿瓦提县| 会理县| 博湖县| 天台县| 曲靖市| 邢台市| 沅江市| 灌云县| 合阳县| 兰坪| 子长县| 大竹县| 常州市| 彩票| 扎赉特旗| 平和县| 徐汇区| 张家港市| 灵璧县| 盐山县| 岐山县| 蓬莱市| 社旗县| 屏东市|