# 与 Stencil 一起使用
¥Usage with Stencil
这些 XState v4 文档不再维护
XState v5 现已推出!阅读有关 XState v5 的更多信息 (opens new window) 和 查看 XState v5 文档 (opens new window)。
¥XState v5 is out now! Read more about XState v5 (opens new window) and check out the XState v5 docs (opens new window).
Stencil (opens new window) Web 组件与 XState 配合得很好。
¥Stencil (opens new window) web components work very well with XState.
# src/helpers/toggle-machine.ts
import { createMachine } from 'xstate';
export const toggleMachine = createMachine({
id: 'toggle',
initial: 'active',
states: {
inactive: { on: { toggle: 'active' } },
active: { on: { toggle: 'inactive' } }
}
});
# src/components/toggle/toggle.tsx
将 state 属性添加到你的组件中,并用 @State 装饰,以便在更改时触发重新渲染。
¥Add a state property to your component, decorated with @State so that it triggers a re-render when changed.
在 componentWillLoad 上,解释 toggleMachine 并监听状态转换。
¥On componentWillLoad, interpret the toggleMachine and listen for state transitions.
发生转换后,state 属性将设置为计算机的新状态,从而触发重新渲染。
¥After a transition has occurred, the state property is set to the machine's new state, triggering a re-render.
import { Component, h, State } from "@stencil/core";
import { interpret } from "xstate";
import { toggleMachine } from "../helpers/toggle-machine";
@Component({
tag: "my-toggle",
styleUrl: "toggle.css",
shadow: true
})
export class Toggle {
private _service = interpret(toggleMachine);
@State() state = this._service.getSnapshot();
componentWillLoad() {
this._service.subscribe(state => {
this.state = state;
});
this._service.start();
}
disconnectedCallback() {
this._service.stop();
}
render() {
const { send } = this._service;
return (
<button onClick={() => send("toggle")}>
{this.state.value === "inactive" ? "Off" : "On"}
</button>
);
}
}
你的 html 页面:
¥Your html page:
<html>
<head>
<script type="module" src="/build/my-toggle.esm.js"></script>
<script nomodule src="/build/my-toggle.js"></script>
</head>
<body>
<my-toggle></my-toggle>
</body>
</html>