本文根据 Devhints / Stencil 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2019-05-08。
Stencil 这是由 Ionic 团队开发的 Web 组件编译器。本指南针对 Stencil v0.0.5。
快速入门指南
入门
JavaScript
import { Component, Prop, State } from '@stencil/core'
@Component({
tag: 'my-component',
styleUrl: 'my-component.scss'
})
export class MyComponent {
@Prop() name: string
@State() isVisible: boolean = true
render () {
return <p>I am {this.name}!</p>
)
}
}
HTML
<my-component name='Groot' />
这是同一个示例,位于 自述文件 (Readme)中的示例相同,用法非常简单!只需使用 <my-component> 像使用任何其他 HTML 标签一样使用它。
DOM 事件
export class MyComponent {
render () {
return (
<input
onChange={(event: UIEvent) => this.inputChanged(event)}
/>
)
}
inputChanged (event) {
console.log('input changed:', event.target.value)
}
}
Stencil 使用 DOM 事件。
参见: 处理用户输入
多个子元素
render () {
return [
<h1>Hello there</h1>,
<p>This component returns multiple nodes</p>
]
}
render() 可以返回一个元素数组。
参见: 复杂的模板内容
状态
管理状态
export class MyComponent {
@State() isVisible: boolean
show () {
this.isVisible = true
}
}
直接进行赋值即可。注意,不能直接修改(即进行“突变”操作),详情请见下一节。
参见: 管理组件状态
更新数组和对象
✗ 不推荐
this.names.push('Larry') // ⚠️
this.options.show = true // ⚠️
✓ OK
this.names = [ ...this.names, 'Larry' ]
this.options = { ...this.options, show: true }
诸如……之类的可变操作(直接修改原对象/数组) push() 是无效的。你需要赋值一个新的副本。
参见: 更新数组
插槽 (Slots)
使用插槽
<my-component>
<span>Hello, friends</span>
</my-component>
组件
render() {
return <h1><slot /></h1>
}
你可以将 JSX/HTML 作为子元素传入。在组件内部,使用 slot 标签来使用它们。
参见: 插槽 (Slots)
多个插槽
<my-component>
<p slot='my-header'>Hello</p>
<p slot='my-footer'>Thanks</p>
</my-component>
组件
render () {
return <div>
<header><slot name='my-header' /></header>
<footer><slot name='my-footer' /></footer>
</div>
}
参见: 插槽 (Slots)
生命周期
生命周期钩子
| 事件 | 说明 |
|---|---|
componentWillLoad() | 渲染前 |
componentDidLoad() | 渲染后 |
componentWillUpdate() | 更新前 |
componentDidUpdate() | 更新后 |
componentDidUnload() | 卸载后 |
参见: 组件生命周期
示例
export class MyComponent {
componentWillUpdate () {
console.log('updating')
}
}
参考资料
- Stencil 文档 (stenciljs.com)