ReactJS——片段


在構建 ReactJS 應用程式時,所有 JSX 程式碼都需要包裝在父級標籤內。

ReactJS 片段在 React 16.2 版本中引入,以消除定義額外 <div> 標籤的需要,該標籤還會佔據額外的記憶體。

不含片段

以下示例程式碼演示瞭如何在不使用 React 片段的情況下建立一個簡單的 React 應用程式。

示例

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h2>TutorialsPoint</h2>
            <p>Simply Easy Learning</p>
         </div>
      );
   }
}
export default App;

輸出

使用片段

在上述示例中,我們必須使用額外的 <div> 標籤來包裝子級 JSX 元素。因此,使用 ReactJS 16.2 版本,我們將使用 React.Fragment,這將消除使用無關的 <div> 標籤的需要。

示例

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <React.Fragment>
            <h2>TutorialsPoint</h2>
            <p>Simply Easy Learning</p>
         </React.Fragment>
      );
   }
}
export default App;

輸出

片段簡寫

我們還可以使用 <> 而不是 React.Fragment,但是此簡寫語法不接受 key 屬性。

示例

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <>
            <h2>TutorialsPoint</h2>
            <p>Simply Easy Learning</p>
         </>
      );
   }
}
export default App;

輸出

更新於: 18-Mar-2021

366 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告