クイックリファレンス

Stencil チートシート

Stencil.js Web Component コンパイラーのクイックリファレンス:デコレータ、props、state、slot、ライフサイクルの解説。

· 公開日

クイックスタートガイド

コンポーネントの定義

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

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.scss',
  shadow: true
})
export class MyComponent {
  @Prop() name: string
  @State() isVisible: boolean = true

  render() {
    return <p>I am {this.name}!</p>
  }
}
<my-component name="Groot"></my-component>

DOM イベントのハンドリング

export class MyComponent {
  inputChanged(event: UIEvent) {
    console.log('input changed:', (event.target as HTMLInputElement).value)
  }

  render() {
    return (
      <input onChange={(e: UIEvent) => this.inputChanged(e)} />
    )
  }
}

複数の子ノードの返却

render() {
  return [
    <h1>Hello there</h1>,
    <p>This component returns multiple root nodes</p>
  ]
}

ステート管理

ステートの更新

export class MyComponent {
  @State() isVisible: boolean = false

  show() {
    this.isVisible = true
  }
}

配列とオブジェクトのイミュータビリティ(不変性)

破壊的な直接変更(In-place Mutation)の回避

// Avoid in-place mutations
this.names.push('Larry')
this.options.show = true

新しい参照を代入して再描画をトリガー

// Trigger re-render by assigning new instances
this.names = [...this.names, 'Larry']
this.options = { ...this.options, show: true }

Slots(スロット)

デフォルトスロット

<my-component>
  <span>Hello, friends</span>
</my-component>
render() {
  return <h1><slot /></h1>
}

名前付きスロット (Named Slots)

<my-component>
  <p slot="my-header">Header Content</p>
  <p slot="my-footer">Footer Content</p>
</my-component>
render() {
  return (
    <div>
      <header><slot name="my-header" /></header>
      <footer><slot name="my-footer" /></footer>
    </div>
  )
}

ライフサイクルフック

ライフサイクルフック 実行タイミング / 説明
componentWillLoad() 初回のレンダリング前に一度だけ実行
componentDidLoad() 初回レンダリング完了後に一度だけ実行
componentWillUpdate() state または prop の変更による再描画前に実行
componentDidUpdate() 再描画が完了した直後に実行
disconnectedCallback() 要素が DOM から削除されたときに実行

参考リンク

関連テーマ