メインコンテンツまでスキップ
バージョン: v4.43

コンポーネントAPI

Stencilが提供するAPIは、デコレータ、ライフサイクルフック、レンダリングメソッドのセットに凝縮されています。

デコレータ​

デコレータは、コンポーネントに関するすべてのメタデータ、プロパティ、属性、メソッド、イベント、関連するスタイルシートを収集するために、Stencilによって使用される、コンパイラ時のためのAPIです。 すべてのメタデータが収集された後、出力からすべての装飾要素を除去します。これにより、実行時のオーバーヘッドが発生しません。

  • @Component() は、新しいウェブコンポーネントの宣言します。
  • @Prop() は、公開されたプロパティ/属性を宣言します。
  • @State()は、コンポーネントの内部状態を宣言します。
  • @Watch() は、プロパティや状態が変化したときに実行されるフックを宣言します。
  • @Element() は、ホスト要素への参照を宣言します。
  • @Method() は、公開されたパブリックメソッドを宣言します。
  • @Event() は、コンポーネントが発する可能性のあるDOMイベントを宣言します。
  • @Listen() は、DOMイベントを監視します。
  • @AttrDeserialize()は、コンポーネントの属性文字列をその JSプロパティに変換するためのハックを宣言しています。
  • @PropSerialize()は、コンポーネントの JSプロパティをその属性文字列に変換するハックを宣言しています。
  • @AttachInternals()は、ElementInternalsをあるコンポーネントに接続します。

ライフサイクル・フック​

componentOnReady()​

これは、trueの「ライフサイクル」メソッドではありません。つまり、コンポーネントクラスの定義に記載されるわけではありません。代わりに、 Stencilコンポーネントを利用する実装側が使用できるユーティリティメソッドです。これにより、コンポーネントが最初のレンダリングサイクルを完了したかどうかを判断することができます。

このメソッドは、初回 のレンダリングサイクルで componentDidRender() が完了した後に解決する Promise を返します。

注記

componentOnReady()は、コンポーネントの寿命の中で一度だけ解決されます。もし、その後のレンダリングサイクルに介入したい場合は、 componentDidRender()やcomponentDidUpdate()を使用してください。

componentOnReady()が解決した後にコードを実行すると、次のような形になるでしょう:

// Get a reference to the element
const el = document.querySelector('my-component');

el.componentOnReady().then(() => {
// Place any code in here you want to execute when the component is ready
console.log('my-component is ready');
});

componentOnReady()の利用可能性は、そのコンパイルされた出力の型に依存します。この方法は、遅延ロードの場合にのみ利用可能です。 分布タイプ(distおよび www)に関しては、利用できない状態です。 dist-custom-elementsの出力です。もし、非遅延型のビルドにおいて、componentOnReady()の動作をシミュレートしたい場合は… Ionic Framework の実装例のように、この処理をまとめるヘルパーメソッドを実装できます。

The appload event​

コンポーネント固有のライフサイクルフックに加えて、アプリとそのすべての子コンポーネントの読み込みが完了すると、apploadと呼ばれる特別なイベントが発行されます。 windowオブジェクトでそのイベントをハンドリングできます。

同じページにStencilアプリがある場合は、 event.detail.namespaceを確認することで、どのアプリがイベントを発行したかを判断できます。これは、Stencilのconfigで設定したnamespace config optionの値になります。

window.addEventListener('appload', (event) => {
console.log(event.detail.namespace);
});

その他​

以下のプリミティブオブジェクトは、@stencil/coreパッケージからインポートでき、コンポーネントのライフサイクル内で使用することができます。

Host:​

<Host>は、レンダリング関数のルート部分で使用できる機能的なコンポーネントです。これを使って、ホスト要素自体に属性やイベントリスナーを設定することができます。使用方法については、ホスト要素のページを参照してください。

Fragment:​

<Fragment>は、<>...</>構文を通じてよく使用されます。これにより、ラッパーノードなしで要素をグループ化することができます。

この機能を使用するには、以下の TypeScriptコンパイラオプションを設定しておく必要があります。

Type: FunctionalComponent
Example:

import { Component, Fragment, h } from '@stencil/core'
@Component({
tag: 'cmp-fragment',
})
export class CmpFragment {
render() {
return (
<>
<div>...</div>
<div>...</div>
<div>...</div>
</>
);
}
}

h():​

JSXの構文を、仮想的な DOM要素に変換します。詳細については、Templating and JSXのページをご覧ください。

render():​

h()によって作成された仮想 DOMを、コンテナ内にレンダリングするためのユーティリティメソッドです。

Type: (vnode: VNode, container: Element) => void Example:

import { render } from '@stencil/core'
const vdom = (
<div className="m-2">Hello World!</div>
)
render(vdom, document.body)

readTask():​

DOM読み取りタスクをスケジュールします。指定されたコールバックは、レイアウトの再計算を引き起こさないような最適なタイミングで実行されます。

Type: (task: Function) => void

writeTask():​

DOMの書き込みタスクをスケジュールします。指定されたコールバックは、レイアウトの再計算を引き起こさないような最適なタイミングで実行されます。

Type: (task: Function) => void

forceUpdate():​

指定されたインスタンスや要素のレンダリングを、状態に変更がない場合でも新たに実行します。なお、forceUpdate()は同期処理ではないため、DOMのレンダリングは次のフレームで行われる可能性があります。

Type: (ref: any) => void
Example:

import { forceUpdate } from '@stencil/core'

// inside a class component function
forceUpdate(this);

getAssetPath():​

ローカルアセットのパスを取得します。使用方法については、アセットのページを参照してください。

Type: (path: string) => string
Example:

import { Component, Prop, getAssetPath, h } from '@stencil/core'
@Component({
tag: 'cmp-asset',
})
export class CmpAsset {
@Prop() icon: string;

render() {
return (
<img src={getAssetPath(`assets/icons/${this.icon}.png`)} />
);
}
}

setAssetPath():​

Stencilがローカルアセットを解決するためのパスを設定します。使用方法については、アセットのページを参照してください。

Type: (path: string) => string
Example:

import { setAssetPath } from '@stencil/core';
setAssetPath(`{window.location.origin}/`);

setMode():​

コンポーネントのスタイルモードを設定します。使用法については、Stylingのページを参照してください。

Type: ((elm: HTMLElement) => string | undefined | null) => void
Example:

import { setMode } from '@stencil/core'

// set mode based on a property
setMode((el) => el.getAttribute('mode'));

getMode():​

アプリケーションの現在のスタイルモードを取得してください。使用法については、Stylingのページを参照してください。

Type: (ref: any) => string | undefined
Example:

import { getMode } from '@stencil/core'

getMode(this);

getElement():​

指定された参照に対応する Stencil要素を取得します。

Type: (ref: any) => HTMLStencilElement
Example:

import { getElement } from '@stencil/core'

const stencilComponent = getElement(document.querySelector('my-cmp'))
if (stencilComponent) {
stencilComponent.componentOnReady().then(() => { ... })
}

resolveVar():​

Stencilのデコレータは、静的な解析に大きく依存しているため、その中で動的な変数を使用することはできません。resolveVarでは、コンパイル時に、指定された変数の文字列値を確定的に得る方法が提供されています。

Type: (variable: T) => string
Example:

import { Listen, Event, resolveVar } from '@stencil/core`

const COMPONENT_A_EVENT: string = 'componentAEvent';
const EVENTS = {
COMPONENT_B_EVENT: 'componentBEvent',
};

// inside an @Component class

@Component({
tag: 'dynamic-event-names',
})
export class DynamicEventNames {
@Event({ eventName: resolveVar(COMPONENT_A_EVENT) }) myEvent;

@Listen(resolveVar(EVENTS.COMPONENT_B_EVENT))
listenHandler(){
//
}
}

Mixin():​

ファクトリ関数を使用して、複数のクラスを一つのコンストラクタにまとめます。

Type:

<TMixins extends readonly MixinFactory[]>(
...mixinFactories: TMixins
): abstract new (...args: any[]) => UnionToIntersection<InstanceType<ReturnType<TMixins[number]>>>;

Example:

import { Mixin, MixedInCtor, Component, h, Prop, State } from '@stencil/core'

const aFactory = <B extends MixedInCtor>(Base: B) => {
class A extends Base { propA = 'A' };
return A;
}
const bFactory = <B extends MixedInCtor>(Base: B) => {
class B extends Base { @Prop() propB = 'B' };
return B;
}
const cFactory = <B extends MixedInCtor>(Base: B) => {
class C extends Base { @State() propC = 'C' };
return C;
}

@Component({
tag: 'its-mixing-time',
})
export class X extends Mixin(aFactory, bFactory, cFactory) {
render() {
return <div>{this.propA} {this.propB} {this.propC}</div>
}
}
注意

Stencil コンポーネントライブラリで Mixin()(または extends)を使用し、ほかの Stencil ライブラリからも使われる 可能性がある 場合、すべての mixin ファクトリーを直接インポートしてください。barrel ファイルは 経由しないでください。 Stencilが使用する静的解析機能は、サードパーティ製のバレルファイルでは機能しない。

Mixin()および extendsをコンポーネントアーキテクチャで使用する際の詳細なガイドについては、どの時点で継承パターンを、またはコンポジションパターンを使用すべきかについては、Extends & Mixinsのガイドを参照してください。

setTagTransformer() and transformTag():​

実行時にタグ名の変換を管理します。使用方法については、Tag Transformationのページを参照してください。