Szybka pomoc

Ściągawka ze Stencil.js

Szybki przewodnik po kompilatorze Web Components Stencil.js: dekoratory, props, state, sloty i cykl życia komponentów.

· Opublikowano

Szybki start

Definicja komponentu

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>

Obsługa zdarzeń 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)} />
    )
  }
}

Zwracanie wielu węzłów potomnych

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

Zarządzanie stanem

Aktualizacja stanu

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

  show() {
    this.isVisible = true
  }
}

Niezmienność dla tablic i obiektów

Unikanie bezpośredniej modyfikacji obiektów

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

Tworzenie nowych referencji w celu wywołania renderowania

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

Sloty

Domyślny slot

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

Sloty nazwane

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

Hooki cyklu życia

Hook cyklu życia Moment wywołania / Opis
componentWillLoad() Wywoływany raz przed pierwszym renderowaniem
componentDidLoad() Wywoływany raz po początkowym renderowaniu
componentWillUpdate() Wywoływany przed ponownym renderowaniem ze względu na zmianę stanu/props
componentDidUpdate() Wywoływany po zakończeniu ponownego renderowania
disconnectedCallback() Wywoływany, gdy element zostaje usunięty z drzewa DOM

Źródła i dokumentacja

Powiązane tematy