ReactJS - 元件佈局



React 的一個高階特性是允許使用屬性將任意使用者介面 (UI) 內容傳遞到元件中。與 React 的特殊 children 屬性相比,後者只允許將單個使用者介面內容傳遞到元件中,此選項允許將多個 UI 內容傳遞到元件中。此選項可以看作是 children 屬性的擴充套件。此選項的用例之一是佈局元件的使用者介面。

例如,具有可自定義頁首和頁尾的元件可以使用此選項透過屬性獲取自定義頁首和頁尾並佈局內容。

示例

下面是一個帶有兩個屬性 headerfooter 的快速簡單的示例

<Layout header={<h1>Header</h1>} footer={<p>footer</p>} />

佈局渲染邏輯如下:

return (<div>
   <div> 
      {props.header} 
   </div> 
   <div> 
      Component user interface 
   </div> 
   <div> 
      {props.footer} 
   </div> 
</div>)

讓我們向我們的支出條目列表 (ExpenseEntryItemList) 元件新增一個簡單的頁首和頁尾。

在您喜歡的編輯器中開啟 expense-manager 應用程式。

接下來,開啟 src/components 資料夾中的 ExpenseEntryItemList.js 檔案。

接下來,在 render() 方法中使用 headerfooter props。

return (
   <div> 
      <div>{this.props.header}</div> 
         ... existing code ... 
      <div>{this.props.footer}</div> 
   </div> 
);

接下來,開啟 index.js 並使用 ExpenseEntryItemList 元件時包含 headerfooter 屬性。

ReactDOM.render(
   <React.StrictMode>
      <ExpenseEntryItemList items={items}
         header={
            <div><h1>Expense manager</h1></div>
         }
         footer={
            <div style={{ textAlign: "left" }}>
               <p style={{ fontSize: 12 }}>Sample application</p>
            </div>
         } 
      />
   </React.StrictMode>,
   document.getElementById('root')
);

接下來,使用 npm 命令啟動應用程式。

npm start

接下來,開啟瀏覽器並在位址列中輸入 https://:3000 並按 Enter 鍵。

Interface

在元件中共享邏輯,又名 Render props

Render props 是用於在 React 元件之間共享邏輯的高階概念。正如我們之前瞭解到的,元件可以透過屬性接收任意 UI 內容或 React 元素(物件)。通常,元件會按原樣渲染它接收到的 React 元素以及它自己的使用者介面,就像我們在 children 和佈局概念中看到的那樣。它們之間不共享任何邏輯。

更進一步,React 允許元件透過屬性獲取一個返回使用者介面而不是普通使用者介面物件的函式。該函式的唯一目的是渲染 UI。然後,元件將進行高階計算,並將呼叫傳入的函式以及計算值來渲染 UI。

簡而言之,接收一個渲染使用者介面的 JavaScript 函式作為屬性的元件稱為 Render Props。接收 Render Props 的元件將執行高階邏輯並將其與 Render Props 共享,後者將使用共享的邏輯渲染使用者介面。

許多高階第三方庫都基於 Render Props。一些使用 Render Props 的庫包括:

  • React Router
  • Formik
  • Downshift

例如,Formik 庫元件將執行表單驗證和提交,並將表單設計傳遞給呼叫函式,即 Render Props。類似地,React Router 執行路由邏輯,同時使用 Render Props 將 UI 設計委派給其他元件。

廣告