随着 React 16 的引入,我们现在可以使用组件、元素和/或字符串的数组来返回组件的渲染方法中的多个子元素。
1class App extends Component {
2 render() {
3 return [
4 <Card key="1" />,
5 'Just a text node',
6 <Card key="2" title="Hello" content="I'm just a card in the world" />
7 ];
8 }
9}
<$>[注]能够返回多个元素的好处是,我们不必包含包裹我们的元素和混乱DOM的不必要的DIV元素。
而这在无状态功能组件(SFCs)中运行得很好:
1const App = () => {
2 return [
3 <Card key="1" />,
4 'Just a text node',
5 <Card key="2" title="Hello" content="I'm just a card in the world" />
6 ];
7};
问题在于使用数组的语法有点尴尬,我们需要为元素添加一个独特的密钥。
插入反應片段
使用 Fragment 组件,我们现在可以完成同样的事情,而不使用数组语法和不使用键。
1import React, { Component } from 'react';
2
3class App extends Component {
4 render() {
5 return (
6 <React.Fragment>
7 <Card />
8 Just a text node
9 <Card title="Hello" content="I'm just a card in the world" />
10 </React.Fragment>
11 );
12 }
13}
我们可以通过直接导入 Fragment 组件来简化语法:
1import React, { Component, Fragment } from 'react';
2
3class App extends Component {
4 render() {
5 return (
6 <Fragment>
7 <Card />
8 Just a text node
9 <Card title="Hello" content="I'm just a card in the world" />
10 </Fragment>
11 );
12 }
13}
<> </> 短语法
您可以通过使用新的<>``</>
短语句来实现概括性:
1import React, { Component } from 'react';
2
3class App extends Component {
4 render() {
5 return (
6 <>
7 <Card />
8 Just a text node
9 <Card title="Hello" content="I'm just a card in the world" />
10 </>
11 );
12 }
13}
Babel 7 在本文写作时仍处于测试阶段,需要将这个短语语法正确地转换为<React.Fragment>
等级。
目前的稳定版本 Create React App 使用 Babel 6.x 在帽子底下,所以短语语法不会直接工作。
1$ yarn add react-scripts@next
<$>[警告] 请注意,当我们使用<React.Fragment>
语法时,我们可以向片段组件添加插件,但不是使用短语语法时。