Ghid de pornire rapidă
Definirea componentei
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>
Gestionarea evenimentelor 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)} />
)
}
}
Returnarea mai multor noduri copil
render() {
return [
<h1>Hello there</h1>,
<p>This component returns multiple root nodes</p>
]
}
Gestionarea stării
Actualizarea stării
export class MyComponent {
@State() isVisible: boolean = false
show() {
this.isVisible = true
}
}
Imutabilitate pentru tablouri și obiecte
Evitarea mutațiilor directe
// Avoid in-place mutations
this.names.push('Larry')
this.options.show = true
Crearea de noi referințe pentru a declanșa re-randarea
// Trigger re-render by assigning new instances
this.names = [...this.names, 'Larry']
this.options = { ...this.options, show: true }
Sloturi
Slot implicit
<my-component>
<span>Hello, friends</span>
</my-component>
render() {
return <h1><slot /></h1>
}
Sloturi cu nume
<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>
)
}
Hook-uri de ciclu de viață
| Hook de ciclu de viață | Moment / Descriere |
|---|---|
componentWillLoad() |
Apelat o singură dată înainte de prima randare |
componentDidLoad() |
Apelat o singură dată după randarea inițială |
componentWillUpdate() |
Apelat înainte de re-randare la modificarea state/prop |
componentDidUpdate() |
Apelat după ce re-randarea s-a încheiat |
disconnectedCallback() |
Apelat când elementul este eliminat din DOM |