Краткий справочник

Шпаргалка по Stencil.js

Краткое руководство по компилятору Web Components Stencil.js: декораторы, props, state, слоты и жизненный цикл компонентов.

· Опубликовано

Краткое руководство по началу работы

Определение компонента

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
  }
}

Неизменяемость (Immutability) для массивов и объектов

Избегайте прямого мутирования объектов

// 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>
}

Именованные слоты

<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

Ссылки и документация

Связанные темы