mcpField
W
web-component-design

web-component-design

github.com/wshobson设计与 UI41.9k13.3k 次安装2 周前更新
代码仓库

关于 web-component-design

为前端开发者提供可复用 UI 组件的设计与实现指导,涵盖组合模式、样式方案和组件 API,并涉及 React、Vue 与 Svelte。

主要功能

  1. 01组件组合模式
  2. 02CSS-in-JS 方案选择
  3. 03组件 API 设计
  4. 04React、Vue 和 Svelte 模式
  5. 05无障碍与响应式实践

适用场景

  1. 01设计组件库或设计系统
  2. 02将复杂 UI 拆分为组合组件
  3. 03重构旧组件
  4. 04改善键盘与屏幕阅读器支持

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshobson/agents --skill web-component-design

安装后在 Claude Code 中输入/web-component-design确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
accessibility-patterns.md
component-patterns.md
css-styling-approaches.md

详细介绍

Web Component 设计

使用现代框架构建可复用、可维护的 UI 组件,采用清晰的组合模式与样式方案。

何时使用本技能

  • 设计可复用的组件库或设计系统
  • 实现复杂的组件组合模式
  • 选择并应用 CSS-in-JS 方案
  • 构建可访问、响应式的 UI 组件
  • 在代码库中创建一致的组件 API
  • 将旧组件重构为现代模式
  • 实现复合组件或 render props

核心概念

1. 组件组合模式

复合组件:协同工作的相关组件

// Usage
<Select value={value} onChange={setValue}>
  <Select.Trigger>Choose option</Select.Trigger>
  <Select.Options>
    <Select.Option value="a">Option A</Select.Option>
    <Select.Option value="b">Option B</Select.Option>
  </Select.Options>
</Select>

Render Props:将渲染委托给父组件

<DataFetcher url="/api/users">
  {({ data, loading, error }) =>
    loading ? <Spinner /> : <UserList users={data} />
  }
</DataFetcher>

插槽(Vue/Svelte):具名内容注入点

<template>
  <Card>
    <template #header>Title</template>
    <template #content>Body text</template>
    <template #footer><Button>Action</Button></template>
  </Card>
</template>
2. CSS-in-JS 方案
方案方式最适合
Tailwind CSS工具类快速原型开发、设计系统
CSS Modules作用域 CSS 文件现有 CSS、渐进式采用
styled-components模板字面量React、动态样式
Emotion对象/模板样式灵活、对 SSR 友好
Vanilla Extract零运行时性能关键型应用
3. 组件 API 设计
interface ButtonProps {
  variant?: "primary" | "secondary" | "ghost";
  size?: "sm" | "md" | "lg";
  isLoading?: boolean;
  isDisabled?: boolean;
  leftIcon?: React.ReactNode;
  rightIcon?: React.ReactNode;
  children: React.ReactNode;
  onClick?: () => void;
}

原则:

  • 使用语义化的 prop 名称(isLoading 而非 loading)
  • 提供合理的默认值
  • 通过 children 支持组合
  • 允许通过 className 或 style 覆盖样式

快速开始:使用 Tailwind 的 React 组件

import { forwardRef, type ComponentPropsWithoutRef } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";

const buttonVariants = cva(
  "inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        primary: "bg-blue-600 text-white hover:bg-blue-700",
        secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200",
        ghost: "hover:bg-gray-100 hover:text-gray-900",
      },
      size: {
        sm: "h-8 px-3 text-sm",
        md: "h-10 px-4 text-sm",
        lg: "h-12 px-6 text-base",
      },
    },
    defaultVariants: {
      variant: "primary",
      size: "md",
    },
  },
);

interface ButtonProps
  extends
    ComponentPropsWithoutRef<"button">,
    VariantProps<typeof buttonVariants> {
  isLoading?: boolean;
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, isLoading, children, ...props }, ref) => (
    <button
      ref={ref}
      className={cn(buttonVariants({ variant, size }), className)}
      disabled={isLoading || props.disabled}
      {...props}
    >
      {isLoading && <Spinner className="mr-2 h-4 w-4" />}
      {children}
    </button>
  ),
);
Button.displayName = "Button";

框架模式

React:复合组件
import { createContext, useContext, useState, type ReactNode } from "react";

interface AccordionContextValue {
  openItems: Set<string>;
  toggle: (id: string) => void;
}

const AccordionContext = createContext<AccordionContextValue | null>(null);

function useAccordion() {
  const context = useContext(AccordionContext);
  if (!context) throw new Error("Must be used within Accordion");
  return context;
}

export function Accordion({ children }: { children: ReactNode }) {
  const [openItems, setOpenItems] = useState<Set<string>>(new Set());

  const toggle = (id: string) => {
    setOpenItems((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  return (
    <AccordionContext.Provider value={{ openItems, toggle }}>
      <div className="divide-y">{children}</div>
    </AccordionContext.Provider>
  );
}

Accordion.Item = function AccordionItem({
  id,
  title,
  children,
}: {
  id: string;
  title: string;
  children: ReactNode;
}) {
  const { openItems, toggle } = useAccordion();
  const isOpen = openItems.has(id);

  return (
    <div>
      <button onClick={() => toggle(id)} className="w-full text-left py-3">
        {title}
      </button>
      {isOpen && <div className="pb-3">{children}</div>}
    </div>
  );
};
Vue 3:组合式函数
<script setup lang="ts">
import { ref, computed, provide, inject, type InjectionKey } from "vue";

interface TabsContext {
  activeTab: Ref<string>;
  setActive: (id: string) => void;
}

const TabsKey: InjectionKey<TabsContext> = Symbol("tabs");

// Parent component
const activeTab = ref("tab-1");
provide(TabsKey, {
  activeTab,
  setActive: (id: string) => {
    activeTab.value = id;
  },
});

// Child component usage
const tabs = inject(TabsKey);
const isActive = computed(() => tabs?.activeTab.value === props.id);
</script>
Svelte 5:Runes
<script lang="ts">
  interface Props {
    variant?: 'primary' | 'secondary';
    size?: 'sm' | 'md' | 'lg';
    onclick?: () => void;
    children: import('svelte').Snippet;
  }

  let { variant = 'primary', size = 'md', onclick, children }: Props = $props();

  const classes = $derived(
    `btn btn-${variant} btn-${size}`
  );
</script>

<button class={classes} {onclick}>
  {@render children()}
</button>

最佳实践

  1. 单一职责:每个组件只做好一件事
  2. 防止 Prop 逐层传递:对深层嵌套数据使用 context
  3. 默认可访问:包含 ARIA 属性、键盘支持
  4. 受控与非受控:在合适时同时支持两种模式
  5. 转发 Refs:允许父组件访问 DOM 节点
  6. 记忆化:对开销大的渲染使用 React.memo、useMemo
  7. 错误边界:包裹可能出错的组件

常见问题

  • Prop 爆炸:prop 过多——考虑改用组合
  • 样式冲突:使用作用域样式或 CSS Modules
  • 重渲染级联:用 React DevTools 分析,适当进行记忆化
  • 可访问性缺口:使用屏幕阅读器和键盘导航进行测试
  • 打包体积:对未使用的组件变体进行 tree-shaking

评论

支持 Markdown