Zag-基于状态机的组件库
本文适合对状态机感兴趣的小伙伴阅读
欢迎关注前端早茶,与广东靓仔携手共同进阶~
一、前言
官方介绍:
Zag 是一个与框架无关的工具包,用于设计系统和 Web 应用程序中实现复杂、交互式和可访问的 UI 组件。
可以在 React、Solid 和 Vue 中构建可访问的 UI 组件,无需为逻辑而烦恼。
过去我们经历了太多与我们如何协调事件、管理状态和副作用有关的小问题和错误。大多数这些错误都与useEffect编排useMemo有关useCallback。
二、Zag的特性
Why Zag?
三、安装
Zag 可以在大多数 JS 框架中使用,例如 Vue、React 和 Solid。
@zag-js/vue

@zag-js/react

@zag-js/solid

为自己感兴趣的组件安装机器
npm i --save @zag-js/{component}
# or
yarn add @zag-js/{component}
# react
npm install @zag-js/react
# or
yarn add @zag-js/react
# vue
npm install @zag-js/vue
# or
yarn add @zag-js/vue
# solid
npm install @zag-js/solid
# or
yarn add @zag-js/solid
四、demo
import { useMachine, useSetup } from "@zag-js/react"
import * as toggle from "@zag-js/toggle"
export function Toggle() {
  const [state, send] = useMachine(toggle.machine)
  const ref = useSetup({ send, id: "1" })
  const api = toggle.connect(state, send)
  return (
    <button ref={ref} {...api.buttonProps}>
      {api.isPressed ? "开" : "关"}
    button>
  )
}
import { computed, defineComponent, h, Fragment } from "vue"
import * as toggle from "@zag-js/toggle"
import { useMachine, useSetup, normalizeProps } from "@zag-js/vue"
export default defineComponent({
  name: "Toggle",
  setup() {
    const [state, send] = useMachine(toggle.machine)
    const ref = useSetup({ send, id: "1" })
    const apiRef = computed(() => toggle.connect(state, send, normalizeProps))
    return () => {
      const api = apiRef.value
      return (
        <button ref={ref} {...api.buttonProps}>
          {api.isPressed ? "开" : "关"}
        button>
      )
    }
  },
})
import { createMemo } from "solid-js"
import * as toggle from "@zag-js/toggle"
import { useMachine, useSetup, normalizeProps } from "@zag-js/solid"
export default function Toggle() {
  const [state, send] = useMachine(toggle.machine)
  const ref = useSetup({ send, id: "1" })
  const api = createMemo(() => toggle.connect(state, send, normalizeProps))
  return (
    <button ref={ref} {...api().buttonProps}>
      {api().isPressed ? "开" : "关"}
    button>
  )
}
面试题库推荐



五、最后
关注我,一起携手进阶
欢迎关注前端早茶,与广东靓仔携手共同进阶~
评论
