コードファーストの開発ワークフローを使って、JSS Next.jsアプリで新しいコンポーネントを作成します
このページの翻訳はAIによって自動的に行われました。可能な限り正確な翻訳を心掛けていますが、原文と異なる表現や解釈が含まれる場合があります。正確で公式な情報については、必ず英語の原文をご参照ください。
新しいコンポーネントの作成は、JSSアプリケーション開発時に最も一般的に行われる作業の一つです。新しいコンポーネントの作成を容易にするために、JSS Next.jsアプリケーションはファイルscripts/scaffold-component.tsで定義されたスキャフォールディングスクリプトを提供します。
この手順は、コードファースト開発ワークフローを用いてJSS Next.jsアプリで 新しいコンポーネントを作成するためのスキャフォールディングスクリプトの方法 を示しています。
!注この手順は、jss create CLIコマンドを使ってプロジェクトを設定したことを前提としています。
Next.js JSSアプリケーションでコンポーネントを作成するには:
-
ターミナルのNext.jsプロジェクトのルートディレクトリで、スクリプトを実行してアプリケーションを起動します:
jss start
!ヒントブラウザでコードの変更をリアルタイムで確認するにはhttp://localhost:3000/ に行ってください。
-
新しいターミナルタブやウィンドウを開いてください。アプリケーションのルートディレクトリで、以下を実行します:
jss scaffold MyComponent
!ヒント足場システムは単純な動作部品を出力します。足場の規則をsrc/scripts/scaffold-component.jsで変更できます。
-
アプリケーションのルートディレクトリにあるファイルsitecore/definitions/components/MyComponent.sitecore.ts 、新しいコンポーネントのマニフェスト定義を含むファイル内で、そのコンポーネントのデータフィールドを定義します。例えば:
// eslint-disable-next-line no-unused-vars import { CommonFieldTypes, SitecoreIcon, Manifest } from '@sitecore-jss/sitecore-jss-manifest';
/** * Adds the MyComponent component to the disconnected manifest. * This function is invoked by convention (*.sitecore.ts) when 'jss manifest' is run. * @param {Manifest} manifest Manifest instance to add components to */ export default function MyComponent(manifest: Manifest): void { manifest.addComponent({ name: 'MyComponent', icon: SitecoreIcon.DocumentTag, fields: { name: 'heading', type: CommonFieldTypes.SingleLineText }, /* If the component implementation uses
or withPlaceholder to expose a placeholder, register it here, or components added to that placeholder will not be returned by Sitecore: placeholders: 'exposed-placeholder-name' */ }); } -
ファイルsrc/components/MyComponent.tsxでReactコンポーネントを実装します。例えば:
import { Text, Field, withDatasourceCheck } from '@sitecore-jss/sitecore-jss-nextjs'; import { StyleguideComponentProps } from 'lib/component-props';
type MyComponentProps = StyleguideComponentProps & { fields: { heading: Field
; }; }; const MyComponent = (props: MyComponentProps): JSX.Element => (
);MyComponent Component
-
新たに作成されたコンポーネントは、ルート上のレイアウトに追加されるまで非アクティブです。コンポーネントをルートレイアウトに追加します。この例では、ルートルートのコンポーネントをデフォルトのプレースホルダーjss-mainに追加します。ファイル /data/routes/en.ymlで、jss-mainプレースホルダーの下にあるコンポーネント配列にコンポーネントを追加します。
placeholders: jss-main:
- componentName: MyComponent fields: heading: Hello, Next.js!
- componentName: ContentBlock fields: heading: Welcome to Sitecore JSS
-
ブラウザを確認してください。新しいコンポーネントはページの上部に表示されます。