React in a common mode component is a plurality of return elements. Fragments allow sub-list groups without having to add additional nodes to the DOM
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
motivation
Do not want to upset the DOM structure or do not want Fragments can be used when additional outer package assembly element, without generating additional Fragments DOM node
usage
1. Explicit usage
class Columns extends React.Component {
render() {
return (
<React.Fragment>
<td>Hello</td>
<td>World</td>
</React.Fragment>
)
}
}
import {Fragment} from 'react';
……
return (
<Fragment>
<WrappedComponent {...newProps} ref={this.wrapperRef} />
<GoTop imgUrl />
</Fragment>
);
……
Using the display <React.Fragment>
syntax for declaring the fragment may have key, key is the only property that can be passed to the Fragment
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// 没有`key`,React 会发出一个关键警告
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
2. The phrase Law
Note: The phrase law or usage does not support the key attributes
class Columns extends React.Component {
render() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
}