- 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>
);
}
推薦閱讀
- Building Django 2.0 Web Applications
- 物聯網檢驗檢測技術
- Learning Karaf Cellar
- 網絡的琴弦:玩轉IP看監控
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- Metasploit Penetration Testing Cookbook
- 物聯網技術與應用
- 圖解手機元器件維修技巧
- Unity Artificial Intelligence Programming
- 6G無線網絡空口關鍵技術
- 端到端QoS網絡設計
- React Cookbook
- Getting Started with nopCommerce
- 無線傳感器網絡定位技術
- Laravel Application Development Cookbook