- React Design Patterns and Best Practices(Second Edition)
- Carlos Santana Roldán
- 254字
- 2021-06-24 15:43:38
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>
);
}
推薦閱讀
- 計算機網(wǎng)絡(luò)與通信(第2版)
- RCNP實驗指南:構(gòu)建高級的路由互聯(lián)網(wǎng)絡(luò)(BARI)
- SOA用戶指南
- 物聯(lián)網(wǎng)智慧安監(jiān)技術(shù)
- 物聯(lián)網(wǎng)安全:理論、實踐與創(chuàng)新
- 重新定義Spring Cloud實戰(zhàn)
- 通信簡史:從信鴿到6G+
- 數(shù)字通信同步技術(shù)的MATLAB與FPGA實現(xiàn):Altera/Verilog版(第2版)
- 物聯(lián)網(wǎng)之霧:基于霧計算的智能硬件快速反應(yīng)與安全控制
- C/C++串口通信:典型應(yīng)用實例編程實踐
- INSTANT KineticJS Starter
- 大型企業(yè)微服務(wù)架構(gòu)實踐與運營
- Qt5 Python GUI Programming Cookbook
- 新媒體交互藝術(shù)
- 加密與解密實戰(zhàn)全攻略