دليل البدء السريع
تعريف المكون
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)} />
)
}
}
إرجاع عدة عقد فرعية (Multiple Nodes)
render() {
return [
<h1>Hello there</h1>,
<p>This component returns multiple root nodes</p>
]
}
إدارة الحالة (State Management)
تحديث الحالة
export class MyComponent {
@State() isVisible: boolean = false
show() {
this.isVisible = true
}
}
ثبات البيانات (Immutability) للمصفوفات والكائنات
تجنب التعديل المباشر (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>
)
}
خطافات دورة الحياة (Lifecycle Hooks)
| خطاف دورة الحياة | التوقيت والوصف |
|---|---|
componentWillLoad() |
يتم استدعاؤه مرة واحدة قبل التصيير الأول |
componentDidLoad() |
يتم استدعاؤه مرة واحدة بعد التصيير الأولي |
componentWillUpdate() |
يتم استدعاؤه قبل إعادة التصيير عند تغير state أو prop |
componentDidUpdate() |
يتم استدعاؤه بعد اكتمال إعادة التصيير |
disconnectedCallback() |
يتم استدعاؤه عند إزالة العنصر من شجرة DOM |