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

コンポーネントAPI

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

デコレータ​

デコレータは、コンポーネントに関するすべてのメタデータ、プロパティ、属性、メソッド、イベント、関連するスタイルシートを収集するために、Stencilによって使用される、コンパイラ時のためのAPIです。 Once all the metadata has been collected, all the decorators are removed from the output, so they don't incur any runtime overhead.

  • @Component() は、新しいウェブコンポーネントの宣言します。
  • @Prop() は、公開されたプロパティ/属性を宣言します。
  • @State() declares an internal state of the component
  • @Watch() は、プロパティや状態が変化したときに実行されるフックを宣言します。
  • @Element() は、ホスト要素への参照を宣言します。
  • @Method() は、公開されたパブリックメソッドを宣言します。
  • @Event() は、コンポーネントが発する可能性のあるDOMイベントを宣言します。
  • @Listen() は、DOMイベントを監視します。

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

componentOnReady()​

This isn't a true "lifecycle" method that would be declared on the component class definition, but instead is a utility method that can be used by an implementation consuming your Stencil component to detect when a component has finished its first render cycle.

This method returns a promise which resolves after componentDidRender() on the first render cycle.

注記

componentOnReady() only resolves once per component lifetime. If you need to hook into subsequent render cycle, use componentDidRender() or componentDidUpdate().

Executing code after componentOnReady() resolves could look something like this:

// 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');
});

The availability of componentOnReady() depends on the component's compiled output type. This method is only available for lazy-loaded distribution types (dist and www) and, as such, is not available for dist-custom-elements output. If you want to simulate the behavior of componentOnReady() for non-lazy builds, you can implement a helper method to wrap the functionality similar to what the Ionic Framework does here.

The appload event​

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

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

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

その他​

The following primitives can be imported from the @stencil/core package and used within the lifecycle of a component:

  • Host: <Host>, is a functional component that can be used at the root of the render function to set attributes and event listeners to the host element itself. Refer to the Host Element page for usage info.

  • Fragment: <Fragment>, often used via <>...</> syntax, lets you group elements without a wrapper node.

    To use this feature, ensure that the following TypeScript compiler options are set:

    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要素に変換するために render() の中で使用されます。

  • render(): a utility method to render a virtual DOM created by h() into a container.

    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(): これは、JSXを仮想DOM要素に変換するために render() の中で使用されます。DOMの読み込みタスクをスケジュールします。提供されたコールバックは、レイアウトスラッシングを起こさずに、DOMの読み込みを実行するために、最適なタイミングで実行されます。

    Type: (task: Function) => void

  • writeTask(): DOM-write タスクをスケジュールします。提供されたコールバックは、レイアウトスラッシングを起こさずに、DOMの突然変異を実行するために最適なタイミングで実行されます。

    Type: (task: Function) => void

  • forceUpdate(): Schedules a new render of the given instance or element even if no state changed. Notice forceUpdate() is not synchronous and might perform the DOM render in the next frame.

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

    import { forceUpdate } from '@stencil/core'

    // inside a class component function
    forceUpdate(this);
  • getAssetPath(): Gets the path to local assets. Refer to the Assets page for usage info.

    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(): Sets the path for Stencil to resolve local assets. Refer to the Assets page for usage info.

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

    import { setAssetPath } from '@stencil/core';
    setAssetPath(`{window.location.origin}/`);
  • setMode(): Sets the style mode of a component. Refer to the Styling page for usage info.

    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(): Get the current style mode of your application. Refer to the Styling page for usage info.

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

    import { getMode } from '@stencil/core'

    getMode(this);
  • getElement(): Retrieve a Stencil element for a given reference.

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

    import { getElement } from '@stencil/core'

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