Communitygithub.com

UI 元件模式

遵循現代設計模式,建構可重複使用、易於維護的 UI 元件。在建立元件庫、實作設計系統或建構可擴展的前端架構時使用。涵蓋 React 模式、組合、Prop 設計、TypeScript 以及元件最佳實務。

UI 元件模式 是什麼?

這個技能為 AI 代理(如 Claude、ChatGPT、Gemini)提供了一套全面的指南,用於建立可重複使用且可維護的 UI 元件。它涵蓋了現代前端開發的五個關鍵步驟:Props API 設計、組合模式、Render Props、透過自訂 Hook 分離邏輯,以及使用 React.memo、useMemo 和 useCallback 進行效能最佳化。該技能強調 TypeScript 型別安全、單一職責原則,並透過 Context 或組合來避免過深的 Prop 傳遞。它提供了真實世界的範例,涵蓋 Button、Card、Dropdown、Modal、Accordion 和多型元件,以及一個建議的檔案結構和元件範本。最終目標是讓開發人員能夠建立遵循設計系統的可擴展元件庫,同時保持程式碼的簡潔、可測試性和可存取性。

相容平台✓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('已點擊!')}>
  點擊我
</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 / 作為函式的 Children

一種彈性自訂的模式。

範例 (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:使用自訂 Hook 分離邏輯

將 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>Hello</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 呼叫和複雜計算

    • 分離到自訂 Hook
  3. 內聯物件/函式:效能下降

    // ❌ 不好的範例
    <Component style={{ color: 'red' }} onClick={() => handleClick()} />
    
    // ✅ 好的範例
    const style = { color: 'red' };
    const handleClick = useCallback(() => {...}, []);
    <Component style={style} onClick={handleClick} />
    

範例

範例 1:Accordion (複合元件)

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="章節 1">
    章節 1 的內容
  </Accordion.Item>
  <Accordion.Item index={1} title="章節 2">
    章節 2 的內容
  </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. 受控 vs 非受控:根據情況選擇
  3. 預設 Props:提供合理的預設值
  4. Storybook:元件文件與開發

參考資料

後設資料

版本

  • 目前版本:1.0.0
  • 最後更新:2025-01-01
  • 相容平台:Claude、ChatGPT、Gemini

相關技能

標籤

#UI-元件 #React #設計模式 #組合 #TypeScript #前端

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

相關技能