빠른 시작 가이드
컴포넌트 정의
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)
직접적인 객체 변형(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>
}
이름이 지정된 슬롯
<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에서 제거될 때 호출됨 |