Οδηγός Γρήγορης Εκκίνησης
Ορισμός Στοιχείου
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
}
}
Αμεταβλητότητα για Πίνακες και Αντικείμενα
Αποφυγή επιτόπιας τροποποίησης
// 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
Προεπιλεγμένο Slot
<my-component>
<span>Hello, friends</span>
</my-component>
render() {
return <h1><slot /></h1>
}
Επώνυμα 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>
)
}
Hooks Κύκλου Ζωής
| Hook Κύκλου Ζωής | Χρονισμός / Περιγραφή |
|---|---|
componentWillLoad() |
Καλείται μία φορά πριν από την πρώτη απόδοση |
componentDidLoad() |
Καλείται μία φορά μετά την αρχική απόδοση |
componentWillUpdate() |
Καλείται πριν από την επανασχεδίαση λόγω αλλαγής state/prop |
componentDidUpdate() |
Καλείται μετά την ολοκλήρωση της επανασχεδίασης |
disconnectedCallback() |
Καλείται όταν το στοιχείο αφαιρεθεί από το DOM |