KScript 文档
ZH

组件

构建你的第一个组件

在你的站点文件夹中创建 _components/click-counter.kscript。

<import package="KScript.Web" />

<type name="ClickCounter" extends="Component">
  <field name="count" type="int" default="0" />

  <fn name="render">
    <return value="```html
        &lt;button type=&quot;button&quot; @on-click(increment: $count)>Count is {$count}&lt;/button>
        ```" />
  </fn>
</type>
import KScript.Web

type ClickCounter extends Component {
  count: int = 0

  fn render() {
    return ```html
    <button type="button" @on-click(increment: $count)>Count is {$count}</button>
    ```
  }
}

在同一个站点文件夹中创建 index.html。

HTML 页面
<h1>Counters</h1>
<click-counter />
<click-counter />

从站点文件夹运行 kscript serve,然后打开它输出的地址。点击第一个按钮,它会显示 Count is 1,而第二个仍显示 Count is 0。

点击处理函数使每个计数器具有交互性。每个实例都有自己的根元素,并在多次点击之间保留自己的 count。传入 <click-counter count="{5}" /> 可使实例从 5 开始。

显式的 <live> 代码块可让你用 as 选择根元素、推迟渲染,或仅使组件的一部分具有交互性。若要在页面中直接放置交互式标记,请使用显式代码块。纯展示组件的渲染无需加载实时运行时。