Communitygithub.com

UI 组件模式

构建可复用、可维护的 UI 组件,遵循现代设计模式。适用于创建组件库、实现设计系统或构建可扩展的前端架构。涵盖 React 模式、组合、属性设计、TypeScript 及组件最佳实践。

UI 组件模式 是什么?

该技能(“UI 组件模式”)为 AI 代理(如 Claude、ChatGPT、Gemini)提供了一套系统化的方法,用于构建高质量、可复用的 React UI 组件。它通过一系列清晰、可执行的步骤,指导代理如何设计 Props API、运用组合模式、使用 Render Props 提供灵活的自定义、利用自定义 Hooks 分离业务逻辑,以及进行性能优化(如 React.memo、useMemo、useCallback)。该技能强调单一职责原则、TypeScript 类型安全、可访问性,并明确禁止过深的 Props 穿透、在 UI 组件中混入业务逻辑以及内联对象/函数等不良实践。最终,代理能够生成结构清晰、易于测试和维护的现代前端组件,适用于从简单按钮到复杂手风琴和多态组件的各种场景。

兼容平台✓Claude Code~Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/supercent-io/ui-component-patterns

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

预览

来自技能 README

UI 组件模式 preview

文档

UI 组件模式 是做什么的?

何时使用此技能

  • 构建组件库:创建可复用的 UI 组件
  • 实现设计系统:应用一致的 UI 模式
  • 复杂 UI:需要多个变体的组件(按钮、模态框、下拉菜单)
  • 重构:将重复代码提取为组件

操作说明

步骤 1:Props API 设计

设计易于使用且可扩展的 Props。

原则:

  • 命名清晰
  • 提供合理的默认值
  • 使用 TypeScript 定义类型
  • 可选 Props 使用可选标记 (?)

示例 (Button):

interface ButtonProps {
  // 必填
  children: React.ReactNode;

  // 可选(有默认值)
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  isLoading?: boolean;

  // 事件处理
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;

  // HTML 属性继承
  type?: 'button' | 'submit' | 'reset';
  className?: string;
}

function Button({
  children,
  variant = 'primary',
  size = 'md',
  disabled = false,
  isLoading = false,
  onClick,
  type = 'button',
  className = '',
  ...rest
}: ButtonProps) {
  const baseClasses = 'btn';
  const variantClasses = `btn-${variant}`;
  const sizeClasses = `btn-${size}`;
  const classes = `${baseClasses} ${variantClasses} ${sizeClasses} ${className}`;

  return (
    <button
      type={type}
      className={classes}
      disabled={disabled || isLoading}
      onClick={onClick}
      {...rest}
    >
      {isLoading ? <Spinner /> : children}
    </button>
  );
}

// 使用示例
<Button variant="primary" size="lg" onClick={() => alert('Clicked!')}>
  点击我
</Button>

步骤 2:组合模式

将小组件组合成复杂的 UI。

示例 (Card):

// Card 组件(容器)
interface CardProps {
  children: React.ReactNode;
  className?: string;
}

function Card({ children, className = '' }: CardProps) {
  return <div className={`card ${className}`}>{children}</div>;
}

// Card.Header
function CardHeader({ children }: { children: React.ReactNode }) {
  return <div className="card-header">{children}</div>;
}

// Card.Body
function CardBody({ children }: { children: React.ReactNode }) {
  return <div className="card-body">{children}</div>;
}

// Card.Footer
function CardFooter({ children }: { children: React.ReactNode }) {
  return <div className="card-footer">{children}</div>;
}

// 复合组件模式
Card.Header = CardHeader;
Card.Body = CardBody;
Card.Footer = CardFooter;

export default Card;

// 使用
import Card from './Card';

function ProductCard() {
  return (
    <Card>
      <Card.Header>
        <h3>产品名称</h3>
      </Card.Header>
      <Card.Body>
        <img src="..." alt="产品" />
        <p>产品描述...</p>
      </Card.Body>
      <Card.Footer>
        <button>加入购物车</button>
      </Card.Footer>
    </Card>
  );
}

步骤 3:Render Props / 函数作为子元素

一种用于灵活自定义的模式。

示例 (Dropdown):

interface DropdownProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  onSelect: (item: T) => void;
  placeholder?: string;
}

function Dropdown<T>({ items, renderItem, onSelect, placeholder }: DropdownProps<T>) {
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState<T | null>(null);

  const handleSelect = (item: T) => {
    setSelected(item);
    onSelect(item);
    setIsOpen(false);
  };

  return (
    <div className="dropdown">
      <button onClick={() => setIsOpen(!isOpen)}>
        {selected ? renderItem(selected, -1) : placeholder || '请选择...'}
      </button>

      {isOpen && (
        <ul className="dropdown-menu">
          {items.map((item, index) => (
            <li key={index} onClick={() => handleSelect(item)}>
              {renderItem(item, index)}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

// 使用
interface User {
  id: string;
  name: string;
  avatar: string;
}

function UserDropdown() {
  const users: User[] = [...];

  return (
    <Dropdown
      items={users}
      placeholder="选择用户"
      renderItem={(user) => (
        <div className="user-item">
          <img src={user.avatar} alt={user.name} />
          <span>{user.name}</span>
        </div>
      )}
      onSelect={(user) => console.log('已选择:', user)}
    />
  );
}

步骤 4:使用自定义 Hooks 分离逻辑

将 UI 与业务逻辑分离。

示例 (Modal):

// hooks/useModal.ts
function useModal(initialOpen = false) {
  const [isOpen, setIsOpen] = useState(initialOpen);

  const open = useCallback(() => setIsOpen(true), []);
  const close = useCallback(() => setIsOpen(false), []);
  const toggle = useCallback(() => setIsOpen(prev => !prev), []);

  return { isOpen, open, close, toggle };
}

// components/Modal.tsx
interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
}

function Modal({ isOpen, onClose, title, children }: ModalProps) {
  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>{title}</h2>
          <button onClick={onClose} aria-label="关闭">×</button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

// 使用
function App() {
  const { isOpen, open, close } = useModal();

  return (
    <>
      <button onClick={open}>打开模态框</button>
      <Modal isOpen={isOpen} onClose={close} title="我的模态框">
        <p>模态框内容...</p>
      </Modal>
    </>
  );
}

步骤 5:性能优化

防止不必要的重新渲染。

React.memo:

// ❌ 错误:每次父组件重渲染时子组件都会重渲染
function ExpensiveComponent({ data }) {
  console.log('渲染中...');
  return <div>{/* 复杂 UI */}</div>;
}

// ✅ 正确:仅在 props 变化时重渲染
const ExpensiveComponent = React.memo(({ data }) => {
  console.log('渲染中...');
  return <div>{/* 复杂 UI */}</div>;
});

useMemo 和 useCallback:

function ProductList({ products, category }: { products: Product[]; category: string }) {
  // ✅ 记忆化过滤结果
  const filteredProducts = useMemo(() => {
    return products.filter(p => p.category === category);
  }, [products, category]);

  // ✅ 记忆化回调
  const handleAddToCart = useCallback((productId: string) => {
    // 加入购物车
    console.log('添加中:', productId);
  }, []);

  return (
    <div>
      {filteredProducts.map(product => (
        <ProductCard
          key={product.id}
          product={product}
          onAddToCart={handleAddToCart}
        />
      ))}
    </div>
  );
}

const ProductCard = React.memo(({ product, onAddToCart }) => {
  return (
    <div>
      <h3>{product.name}</h3>
      <button onClick={() => onAddToCart(product.id)}>加入购物车</button>
    </div>
  );
});

输出格式

组件文件结构

components/
├── Button/
│   ├── Button.tsx           # 主组件
│   ├── Button.test.tsx      # 测试
│   ├── Button.stories.tsx   # Storybook
│   ├── Button.module.css    # 样式
│   └── index.ts             # 导出
├── Card/
│   ├── Card.tsx
│   ├── CardHeader.tsx
│   ├── CardBody.tsx
│   ├── CardFooter.tsx
│   └── index.ts
└── Modal/
    ├── Modal.tsx
    ├── useModal.ts          # 自定义 Hook
    └── index.ts

组件模板

import React from 'react';

export interface ComponentProps {
  // Props 定义
  children: React.ReactNode;
  className?: string;
}

/**
 * 组件描述
 *
 * @example
 * ```tsx
 * <Component>你好</Component>
 * ```
 */
export const Component = React.forwardRef<HTMLDivElement, ComponentProps>(
  ({ children, className = '', ...rest }, ref) => {
    return (
      <div ref={ref} className={`component ${className}`} {...rest}>
        {children}
      </div>
    );
  }
);

Component.displayName = 'Component';

export default Component;

约束

必须遵守的规则

  1. 单一职责原则:一个组件只负责一个角色

    • Button 只处理按钮相关,Form 只处理表单相关
  2. Props 类型定义:必须使用 TypeScript 接口

    • 启用自动补全
    • 类型安全
  3. 可访问性:使用 aria-*、role、tabindex 等

禁止的规则

  1. 过深的 Props 穿透:层级超过 5 层时禁止

    • 使用 Context 或组合
  2. 不含业务逻辑:禁止在 UI 组件中进行 API 调用和复杂计算

    • 分离到自定义 Hooks 中
  3. 内联对象/函数:导致性能下降

    // ❌ 错误示例
    <Component style={{ color: 'red' }} onClick={() => handleClick()} />
    
    // ✅ 正确示例
    const style = { color: 'red' };
    const handleClick = useCallback(() => {...}, []);
    <Component style={style} onClick={handleClick} />
    

示例

示例 1:手风琴(复合组件)

import React, { createContext, useContext, useState } from 'react';

// 使用 Context 共享状态
const AccordionContext = createContext<{
  activeIndex: number | null;
  setActiveIndex: (index: number | null) => void;
} | null>(null);

function Accordion({ children }: { children: React.ReactNode }) {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  return (
    <AccordionContext.Provider value={{ activeIndex, setActiveIndex }}>
      <div className="accordion">{children}</div>
    </AccordionContext.Provider>
  );
}

function AccordionItem({ index, title, children }: {
  index: number;
  title: string;
  children: React.ReactNode;
}) {
  const context = useContext(AccordionContext);
  if (!context) throw new Error('AccordionItem 必须在 Accordion 内部使用');

  const { activeIndex, setActiveIndex } = context;
  const isActive = activeIndex === index;

  return (
    <div className="accordion-item">
      <button
        className="accordion-header"
        onClick={() => setActiveIndex(isActive ? null : index)}
        aria-expanded={isActive}
      >
        {title}
      </button>
      {isActive && <div className="accordion-body">{children}</div>}
    </div>
  );
}

Accordion.Item = AccordionItem;
export default Accordion;

// 使用
<Accordion>
  <Accordion.Item index={0} title="第一节">
    第一节内容
  </Accordion.Item>
  <Accordion.Item index={1} title="第二节">
    第二节内容
  </Accordion.Item>
</Accordion>

示例 2:多态组件(as prop)

type PolymorphicComponentProps<C extends React.ElementType> = {
  as?: C;
  children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;

function Text<C extends React.ElementType = 'span'>({
  as,
  children,
  ...rest
}: PolymorphicComponentProps<C>) {
  const Component = as || 'span';
  return <Component {...rest}>{children}</Component>;
}

// 使用
<Text>默认 span</Text>
<Text as="h1">标题 1</Text>
<Text as="p" style={{ color: 'blue' }}>段落</Text>
<Text as={Link} href="/about">链接</Text>

最佳实践

  1. 组合优于 Props:利用 children 而非大量 Props
  2. 受控与非受控:根据场景选择
  3. 默认 Props:提供合理的默认值
  4. Storybook:组件文档和开发

参考资料

元数据

版本

  • 当前版本:1.0.0
  • 最后更新:2025-01-01
  • 兼容平台:Claude, ChatGPT, Gemini

相关技能

标签

#UI-components #React #design-patterns #composition #TypeScript #frontend

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能