可編輯的React元件可以是「固定」元件,或硬式編碼至SPA檢視。 這可讓開發人員將SPA Editor相容的元件放入SPA檢視中,並讓使用者在AEM SPA Editor中製作元件的內容。
在本章中,我們將首頁檢視的標題「Current Adventures」(目前歷險)取代為固定但可編輯的標題元件,此元件為Home.js
中的硬式編碼文字。 固定元件可保證標題的放置,但也允許編寫標題的文字,並在開發週期之外進行變更。
要將「固定」元件添加到「首頁」視圖:
在SPA首頁檢視中,將硬式編碼文字<h2>Current Adventures</h2>
取代為AEM React核心元件的標題元件。 必須先執行下列動作,才能使用Title元件:
@adobe/aem-core-components-react-base
導入Title元件withMappable
註冊,讓開發人員可將其放入SPAMapTo
,以便以後在容器元件中使用。要執行此操作:
在IDE的~/Code/wknd-app/aem-guides-wknd-graphql/react-app
處開啟遠程SPA項目
在react-app/src/components/aem/AEMTitle.js
建立React元件
將下列程式碼新增至AEMTitle.js
。
// Import the withMappable API provided by the AEM SPA Editor JS SDK
import { withMappable, MapTo } from '@adobe/aem-react-editable-components';
// Import the AEM React Core Components' Title component implementation and it's Empty Function
import { TitleV2, TitleV2IsEmptyFn } from "@adobe/aem-core-components-react-base";
// The sling:resourceType for which this Core Component is registered with in AEM
const RESOURCE_TYPE = "wknd-app/components/title";
// Create an EditConfig to allow the AEM SPA Editor to properly render the component in the Editor's context
const EditConfig = {
emptyLabel: "Title", // The component placeholder in AEM SPA Editor
isEmpty: TitleV2IsEmptyFn, // The function to determine if this component has been authored
resourceType: RESOURCE_TYPE // The sling:resourceType this component is mapped to
};
// MapTo allows the AEM SPA Editor JS SDK to dynamically render components added to SPA Editor Containers
MapTo(RESOURCE_TYPE)(TitleV2, EditConfig);
// withMappable allows the component to be hardcoded into the SPA; <AEMTitle .../>
const AEMTitle = withMappable(TitleV2, EditConfig);
export default AEMTitle;
閱讀程式碼的註解,了解實作詳細資訊。
AEMTitle.js
檔案應該如下所示:
現在AEM React核心元件的標題元件已在中註冊,且可在React應用程式中使用,請取代首頁檢視上的硬式編碼標題文字。
編輯 react-app/src/App.js
在底部的Home()
中,以新的AEMTitle
元件取代硬式編碼標題:
<h2>Current Adventures</h2>
替換為
<AEMTitle
pagePath='/content/wknd-app/us/en/home'
itemPath='root/title'/>
使用下列程式碼更新Apps.js
:
...
import { AEMTitle } from './components/aem/AEMTitle';
...
function Home() {
return (
<div className="Home">
<AEMTitle
pagePath='/content/wknd-app/us/en/home'
itemPath='root/title'/>
<Adventures />
</div>
);
}
Apps.js
檔案應該如下所示:
登入AEM作者
導覽至Sites > WKND App
點選Home並從頂端動作列選取Edit
從頁面編輯器右上角的編輯模式選擇器中選擇Edit
將滑鼠移到WKND標誌下方和歷險清單上方的預設標題文字上,直到顯示藍色的編輯大綱
點選以顯示元件的動作列,然後點選扳手以編輯
製作標題元件:
標題:WKND冒險
類型/大小:H2
點選Done以儲存
在AEM SPA編輯器中預覽變更
重新整理本機在http://localhost:3000上執行的WKND應用程式,並立即查看所撰寫的標題變更。
您已將固定的可編輯元件新增至WKND應用程式! 您現在知道如何:
接下來的步驟是將AEM ResponsiveGrid容器元件新增至SPA,讓作者可將可編輯的元件新增至SPA!