# 任务 1:计数器

¥Task 1: Counter

这是 7GUI 的 7 项任务 (opens new window) 的第一个:

¥This is the first of The 7 Tasks from 7GUIs (opens new window):

挑战:了解语言/工具包的基本思想。

¥Challenge: Understanding the basic ideas of a language/toolkit.

任务是构建一个包含标签或只读文本字段 T 和按钮 B 的框架。最初,T 中的值为“0”,每次点击 B 都会使 T 中的值增加 1。

¥The task is to build a frame containing a label or read-only textfield T and a button B. Initially, the value in T is “0” and each click of B increases the value in T by one.

Counter 是对可以想象到的最简单 GUI 应用之一的语言、范例和工具包基础知识的温和介绍。因此,Counter 揭示了所需的脚手架以及非常基本的功能如何协同工作来构建 GUI 应用。一个好的解决方案几乎不需要脚手架。

¥Counter serves as a gentle introduction to the basics of the language, paradigm and toolkit for one of the simplest GUI applications imaginable. Thus, Counter reveals the required scaffolding and how the very basic features work together to build a GUI application. A good solution will have almost no scaffolding.

# 建模

¥Modeling

在这个简单的 UI 中,只有一个有限状态,可以命名为 "active"。然而,上下文将包含 count,它表示当前计数,初始值为 0,并且可以是无限的。"INCREMENT" 事件将触发上下文更新,根据当前 context.count 值向 count 分配新值。

¥In this simple UI, there is only one finite state, which can be named "active". The context, however, will contain the count, which represents the current count with an initial value of 0 and can be infinite. An "INCREMENT" event will trigger an update to the context which assigns a new value to count based on the current context.count value.

状态:

¥States:

  • "active" - 启用计数的状态

    ¥"active" - the state where counting is enabled

上下文:

¥Context:

  • count - 当前计数值

    ¥count - the current count value

事件:

¥Events:

  • "INCREMENT" - 表示计数应加一

    ¥"INCREMENT" - signals that the count should be increased by one

# 编码

¥Coding

import { createMachine, assign } from 'xstate';

export const counterMachine = createMachine({
  initial: 'active',
  context: { count: 0 },
  states: {
    active: {
      on: {
        INCREMENT: {
          actions: assign({ count: (ctx) => ctx.count + 1 })
        }
      }
    }
  }
});

# 结果

¥Result