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

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>
);
}
主站蜘蛛池模板: 万年县| 吉安市| 黑水县| 甘德县| 隆安县| 江源县| 时尚| 汝城县| 万安县| 沙坪坝区| 泗阳县| 巧家县| 孝感市| 丰镇市| 得荣县| 广昌县| 亚东县| 通许县| 从化市| 池州市| 定结县| 宁津县| 肃南| 启东市| 汕头市| 田阳县| 黎川县| 漯河市| 文安县| 乌拉特前旗| 黎平县| 金塔县| 苗栗县| 芷江| 杭锦后旗| 合作市| 建瓯市| 景德镇市| 孟连| 浠水县| 蓝田县|