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

ホスト要素の操作

Stencil components render their children declaratively in their render method using JSX. Most of the time, the render() function describes the children elements that are about to be rendered, but it can also be used to render attributes of the host element itself.

<Host>​

Host関数コンポーネントをrender関数のルートで使用して、属性とイベントリスナーをホスト要素自体に設定できます。 これは他のJSXと同じように機能します。

// ホストは「@stencil/core」からインポートされます
import { Component, Host, h } from '@stencil/core';

@Component({tag: 'todo-list'})
export class TodoList {
@Prop() open = false;
render() {
return (
<Host
aria-hidden={this.open ? 'false' : 'true'}
class={{
'todo-list': true,
'is-open': this.open
}}
/>
)
}
}

もし this.open === trueの場合、次のようにレンダリングされます。

<todo-list class="todo-list is-open" aria-hidden="false"></todo-list>

similarly, if this.open === false:

<todo-list class="todo-list" aria-hidden="true"></todo-list>

<Host>は仮想コンポーネントであり、ホスト要素の属性を宣言的に設定するためにステンシルによって公開される仮想APIであり、DOMにレンダリングされることはありません。つまり、Chrome DevToolsに <Host>が表示されることはありません。

<Host>は <Fragment>として機能します​

<Host>は、たとえば次のように、ルートレベルで複数のコンポーネントをレンダリングする必要がある場合にも使用できます。

これは、次のような render()メソッドによって実現できます。

@Component({tag: 'my-cmp'})
export class MyCmp {
render() {
return (
<Host>
<h1>Title</h1>
<p>Message</p>
</Host>
);
}
}

このJSXは、次のHTMLをレンダリングします。

<my-cmp>
<h1>Title</h1>
<p>Message</p>
</my-cmp>

<Host>を使用してホスト要素の属性をレンダリングしない場合でも、ルートレベルで多くの要素をレンダリングするのに便利なAPIです。

要素デコレータ​

@Element()デコレータは、クラスインスタンス内のホスト要素にアクセスする方法です。 これは HTMLElementのインスタンスを返すため、ここでは標準のDOMメソッド/イベントを使用できます。

import { Element } from '@stencil/core';

...
export class TodoList {

@Element() el: HTMLElement;

getListHeight(): number {
return this.el.getBoundingClientRect().height;
}
}

In order to reference the host element when initializing a class member you'll need to use TypeScript's definite assignment assertion modifier to avoid a type error:

import { Element } from '@stencil/core';

...
export class TodoList {

@Element() el!: HTMLElement;

private listHeight = this.el.getBoundingClientRect().height;
}

propまたは状態の変更に応じてホスト要素を更新する必要がある場合は、 <Host>要素を使用して render()メソッドで更新する必要があります。

スタイリング​

See full information about styling on the Styling page.

CSSは、@Componentデコレータで定義されたコンポーネントタグを使用して<Host>要素に適用できます。

@Component({
tag: 'my-cmp',
styleUrl: 'my-cmp.css'
})
...

my-cmp.css:

my-cmp {
width: 100px;
}

Shadow DOM​

注意すべき点は、シャドウDOMを使用する場合の <Host>要素のスタイリングはまったく同じようには機能しないということです。 my-cmp要素セレクターを使用する代わりに、:hostを使用する必要があります。

@Component({
tag: 'my-cmp',
styleUrl: 'my-cmp.css',
shadow: true
})
...

my-cmp.css:

:host {
width: 100px;
}