Frontend Component Patterns 标志

Frontend Component Patterns

社区
korallis
frontend-component-patterns

Build reusable, composable, and maintainable React/Vue/Angular components following established design patterns like compound components, render props, custom hooks, and HOCs. Use when creating component libraries, implementing component composition, building reusable UI elements, designing prop APIs, managing component state patterns, implementing controlled vs uncontrolled components, creating compound components, using render props or children as functions, building custom hooks, or establishing component architecture standards.

概览

发布者korallis
代码仓库Droidz
技能名称frontend-component-patterns
星标数
89
复刻数
9
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 korallis 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Frontend Component Patterns AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/korallis/Droidz/tree/main/droidz_installer/payloads/claude/default/skills/frontend-component-patterns
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/korallis/Droidz.git /tmp/Droidz
mkdir -p .claude/skills
cp -r /tmp/Droidz/droidz_installer/payloads/claude/default/skills/frontend-component-patterns .claude/skills/frontend-component-patterns
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Frontend Component Patterns,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Frontend Component Patterns。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Frontend Component Patterns 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Frontend Component Patterns - Building Reusable React Components

When to use this skill

  • Creating reusable component libraries
  • Implementing component composition patterns
  • Building flexible, configurable UI components
  • Designing intuitive component prop APIs
  • Managing component state with patterns
  • Implementing controlled vs uncontrolled components
  • Creating compound components (e.g., Tabs, Accordion)
  • Using render props or children as functions
  • Building custom React hooks for shared logic
  • Implementing Higher-Order Components (HOCs)
  • Establishing component architecture standards
  • Creating accessible, keyboard-navigable components

When to use this skill

  • Designing React component architecture, improving component reusability, managing state, or solving common UI patterns.
  • When working on related tasks or features
  • During development that requires this expertise

Use when: Designing React component architecture, improving component reusability, managing state, or solving common UI patterns.

Core Principles

  1. Composition Over Inheritance - Build complex UIs from simple components
  2. Single Responsibility - Each component does one thing well
  3. Props Down, Events Up - Unidirectional data flow
  4. Separation of Concerns - Logic separate from presentation
  5. Accessibility First - ARIA, keyboard navigation, semantic HTML

Component Patterns

1. Presentational vs Container Components

typescript
// ❌ Mixed concerns - logic + presentation together
function UserProfile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(setUser)
      .finally(() => setLoading(false));
  }, [userId]);
  
  if (loading) return <div>Loading...</div>;
  
  return (
    <div className="profile">
      <img src={user.avatar} alt={user.name} />
      <h1>{user.name}</h1>
      <p>{user.bio}</p>
    </div>
  );
}

// ✅ Separated - Container handles logic
function UserProfileContainer({ userId }: { userId: string }) {
  const { data: user, isLoading } = useUser(userId);
  
  if (isLoading) return <LoadingSpinner />;
  if (!user) return <NotFound />;
  
  return <UserProfileView user={user} />;
}

// ✅ Presentational - Pure display component
interface UserProfileViewProps {
  user: {
    avatar: string;
    name: string;
    bio: string;
  };
}

function UserProfileView({ user }: UserProfileViewProps) {
  return (
    <div className="profile">
      <img src={user.avatar} alt={user.name} />
      <h1>{user.name}</h1>
      <p>{user.bio}</p>
    </div>
  );
}

2. Compound Components

typescript
// ✅ Flexible, composable API
interface TabsProps {
  children: React.ReactNode;
  defaultValue?: string;
}

interface TabsContextValue {
  activeTab: string;
  setActiveTab: (value: string) => void;
}

const TabsContext = React.createContext<TabsContextValue | null>(null);

function Tabs({ children, defaultValue }: TabsProps) {
  const [activeTab, setActiveTab] = useState(defaultValue || '');
  
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div className="tabs">{children}</div>
    </TabsContext.Provider>
  );
}

function TabsList({ children }: { children: React.ReactNode }) {
  return <div className="tabs-list" role="tablist">{children}</div>;
}

function TabsTrigger({ value, children }: { value: string; children: React.ReactNode }) {
  const context = useContext(TabsContext);
  if (!context) throw new Error('TabsTrigger must be inside Tabs');
  
  const isActive = context.activeTab === value;
  
  return (
    <button
      role="tab"
      aria-selected={isActive}
      onClick={() => context.setActiveTab(value)}
      className={isActive ? 'active' : ''}
    >
      {children}
    </button>
  );
}

function TabsContent({ value, children }: { value: string; children: React.ReactNode }) {
  const context = useContext(TabsContext);
  if (!context) throw new Error('TabsContent must be inside Tabs');
  
  if (context.activeTab !== value) return null;
  
  return <div role="tabpanel">{children}</div>;
}

// Export as compound component
export { Tabs, TabsList, TabsTrigger, TabsContent };

// Usage - flexible and intuitive
function App() {
  return (
    <Tabs defaultValue="account">
      <TabsList>
        <TabsTrigger value="account">Account</TabsTrigger>
        <TabsTrigger value="password">Password</TabsTrigger>
        <TabsTrigger value="notifications">Notifications</TabsTrigger>
      </TabsList>
      
      <TabsContent value="account">
        <AccountSettings />
      </TabsContent>
      
      <TabsContent value="password">
        <PasswordSettings />
      </TabsContent>
      
      <TabsContent value="notifications">
        <NotificationSettings />
      </TabsContent>
    </Tabs>
  );
}

3. Render Props Pattern

typescript
// ✅ Flexible rendering with render props
interface MousePositionProps {
  children: (position: { x: number; y: number }) => React.ReactNode;
}

function MousePosition({ children }: MousePositionProps) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  
  useEffect(() => {
    const handleMove = (e: MouseEvent) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };
    
    window.addEventListener('mousemove', handleMove);
    return () => window.removeEventListener('mousemove', handleMove);
  }, []);
  
  return <>{children(position)}</>;
}

// Usage - consumer controls rendering
function App() {
  return (
    <MousePosition>
      {({ x, y }) => (
        <div>
          Mouse is at ({x}, {y})
        </div>
      )}
    </MousePosition>
  );
}

4. Custom Hooks (Modern Alternative)

typescript
// ✅ Extract reusable logic as hook
function useMousePosition() {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  
  useEffect(() => {
    const handleMove = (e: MouseEvent) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };
    
    window.addEventListener('mousemove', handleMove);
    return () => window.removeEventListener('mousemove', handleMove);
  }, []);
  
  return position;
}

// Usage - cleaner than render props
function App() {
  const { x, y } = useMousePosition();
  
  return (
    <div>
      Mouse is at ({x}, {y})
    </div>
  );
}

// ✅ More custom hooks examples
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState(value);
  
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  
  return debouncedValue;
}

function useLocalStorage<T>(key: string, initialValue: T) {
  const [value, setValue] = useState<T>(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });
  
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  
  return [value, setValue] as const;
}

5. Higher-Order Components (Legacy Pattern)

typescript
// ✅ HOC for adding functionality
function withLoading<P extends object>(
  Component: React.ComponentType<P>
) {
  return function WithLoadingComponent(
    props: P & { isLoading: boolean }
  ) {
    if (props.isLoading) {
      return <LoadingSpinner />;
    }
    
    return <Component {...props} />;
  };
}

// Usage
const UserListWithLoading = withLoading(UserList);

<UserListWithLoading users={users} isLoading={loading} />

// Note: Custom hooks are now preferred over HOCs

State Management Patterns

1. Props vs State

typescript
// ✅ Props - passed from parent
interface ButtonProps {
  label: string;        // Display text
  onClick: () => void;  // Callback
  disabled?: boolean;   // Optional config
}

function Button({ label, onClick, disabled }: ButtonProps) {
  return (
    <button onClick={onClick} disabled={disabled}>
      {label}
    </button>
  );
}

// ✅ State - internal to component
function Counter() {
  const [count, setCount] = useState(0); // Local state
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

// ✅ Controlled vs Uncontrolled
// Controlled - value from props (parent controls)
function ControlledInput({ value, onChange }: { 
  value: string; 
  onChange: (value: string) => void; 
}) {
  return (
    <input 
      value={value} 
      onChange={(e) => onChange(e.target.value)} 
    />
  );
}

// Uncontrolled - internal state (component controls)
function UncontrolledInput() {
  const inputRef = useRef<HTMLInputElement>(null);
  
  const handleSubmit = () => {
    console.log(inputRef.current?.value);
  };
  
  return (
    <>
      <input ref={inputRef} defaultValue="initial" />
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}

2. Lifting State Up

typescript
// ❌ Duplicated state - siblings can't communicate
function ParentBad() {
  return (
    <>
      <SearchBox /> {/* Has own search state */}
      <ResultsList /> {/* Has own search state */}
    </>
  );
}

// ✅ Shared state in parent
function ParentGood() {
  const [searchQuery, setSearchQuery] = useState('');
  
  return (
    <>
      <SearchBox query={searchQuery} onQueryChange={setSearchQuery} />
      <ResultsList query={searchQuery} />
    </>
  );
}

3. Context for Deep Props

typescript
// ❌ Prop drilling - passing through many levels
function App() {
  const [theme, setTheme] = useState('light');
  return <Layout theme={theme} setTheme={setTheme} />;
}

function Layout({ theme, setTheme }) {
  return <Sidebar theme={theme} setTheme={setTheme} />;
}

function Sidebar({ theme, setTheme }) {
  return <ThemeToggle theme={theme} setTheme={setTheme} />;
}

// ✅ Context - direct access at any level
interface ThemeContextValue {
  theme: string;
  setTheme: (theme: string) => void;
}

const ThemeContext = createContext<ThemeContextValue | null>(null);

function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) throw new Error('useTheme must be inside ThemeProvider');
  return context;
}

// Usage - no prop drilling
function ThemeToggle() {
  const { theme, setTheme } = useTheme();
  
  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle {theme} theme
    </button>
  );
}

Performance Optimization

1. React.memo - Prevent Re-renders

typescript
// ❌ Re-renders on every parent render
function ExpensiveComponent({ data }: { data: string }) {
  console.log('Rendering...');
  return <div>{data}</div>;
}

// ✅ Only re-renders when props change
const ExpensiveComponent = memo(function ExpensiveComponent({ 
  data 
}: { 
  data: string 
}) {
  console.log('Rendering...');
  return <div>{data}</div>;
});

// ✅ Custom comparison function
const ExpensiveList = memo(
  function ExpensiveList({ items }: { items: Item[] }) {
    return <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
  },
  (prevProps, nextProps) => {
    // Only re-render if items array length changed
    return prevProps.items.length === nextProps.items.length;
  }
);

2. useMemo - Cache Expensive Calculations

typescript
function ProductList({ products, filters }: { products: Product[]; filters: Filters }) {
  // ❌ Recalculates on every render
  const filteredProducts = products.filter(p => matchesFilters(p, filters));
  
  // ✅ Only recalculates when dependencies change
  const filteredProducts = useMemo(() => {
    return products.filter(p => matchesFilters(p, filters));
  }, [products, filters]);
  
  return (
    <div>
      {filteredProducts.map(p => (
        <ProductCard key={p.id} product={p} />
      ))}
    </div>
  );
}

3. useCallback - Stable Function References

typescript
function Parent() {
  const [count, setCount] = useState(0);
  
  // ❌ New function on every render (causes child re-render)
  const handleClick = () => {
    console.log('clicked');
  };
  
  // ✅ Stable function reference
  const handleClick = useCallback(() => {
    console.log('clicked');
  }, []); // No dependencies - never changes
  
  return (
    <>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <MemoizedChild onClick={handleClick} />
    </>
  );
}

const MemoizedChild = memo(function Child({ onClick }: { onClick: () => void }) {
  console.log('Child rendering');
  return <button onClick={onClick}>Click me</button>;
});

4. Code Splitting & Lazy Loading

typescript
// ✅ Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'));
const AdminPanel = lazy(() => import('./AdminPanel'));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <Routes>
        <Route path="/dashboard" element={<HeavyChart />} />
        <Route path="/admin" element={<AdminPanel />} />
      </Routes>
    </Suspense>
  );
}

Accessibility Patterns

1. Semantic HTML & ARIA

typescript
// ✅ Accessible button
function AccessibleButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-label={label}
    >
      {label}
    </button>
  );
}

// ✅ Accessible modal
function Modal({ isOpen, onClose, children }: { 
  isOpen: boolean; 
  onClose: () => void; 
  children: React.ReactNode; 
}) {
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      // Focus trap, ESC key handler, etc.
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);
  
  if (!isOpen) return null;
  
  return (
    <div
      role="dialog"
      aria-modal="true"
      className="modal-overlay"
      onClick={onClose}
    >
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        {children}
        <button onClick={onClose} aria-label="Close modal">×</button>
      </div>
    </div>
  );
}

// ✅ Accessible form
function SignupForm() {
  return (
    <form>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        type="email"
        required
        aria-required="true"
        aria-describedby="email-error"
      />
      <span id="email-error" role="alert" className="error">
        Please enter a valid email
      </span>
      
      <button type="submit">Sign Up</button>
    </form>
  );
}

2. Keyboard Navigation

typescript
// ✅ Keyboard-accessible dropdown
function Dropdown({ options }: { options: string[] }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);
  
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' || e.key === ' ') {
      setIsOpen(!isOpen);
    } else if (e.key === 'ArrowDown') {
      setSelectedIndex((i) => Math.min(i + 1, options.length - 1));
    } else if (e.key === 'ArrowUp') {
      setSelectedIndex((i) => Math.max(i - 1, 0));
    } else if (e.key === 'Escape') {
      setIsOpen(false);
    }
  };
  
  return (
    <div
      role="combobox"
      aria-expanded={isOpen}
      aria-controls="dropdown-options"
      tabIndex={0}
      onKeyDown={handleKeyDown}
    >
      <button onClick={() => setIsOpen(!isOpen)}>
        Select option
      </button>
      
      {isOpen && (
        <ul id="dropdown-options" role="listbox">
          {options.map((opt, i) => (
            <li
              key={opt}
              role="option"
              aria-selected={i === selectedIndex}
              className={i === selectedIndex ? 'selected' : ''}
            >
              {opt}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Component Design Checklist

Structure:
□ Single responsibility per component
□ Presentational vs container separation
□ Proper props typing (TypeScript)
□ Default props defined
□ Prop validation for critical inputs

State Management:
□ State at lowest necessary level
□ Lifted state when needed for sharing
□ Context for deep prop drilling
□ No prop mutations
□ Controlled components for forms

Performance:
□ memo() for expensive components
□ useMemo() for expensive calculations
□ useCallback() for stable callbacks
□ Code splitting for large components
□ Lazy loading for routes

Accessibility:
□ Semantic HTML elements
□ ARIA labels and roles
□ Keyboard navigation support
□ Focus management
□ Screen reader tested

Reusability:
□ Configurable via props
□ Composable with children
□ No hardcoded values
□ Clear, documented API
□ Example usage provided

Resources


Remember: Great components are simple, reusable, accessible, and performant. Start simple, add complexity only when needed.

常见问题

Frontend Component Patterns AI 技能有什么作用?

Build reusable, composable, and maintainable React/Vue/Angular components following established design patterns like compound components, render props, custom hooks, and HOCs. Use when creating component libraries, implementing component composition, building reusable UI elements, designing prop APIs, managing component state patterns, implementing controlled vs uncontrolled components, creating compound components, using render props or children as functions, building custom hooks, or establishing component architecture standards.

为什么在 TypingMind 中使用 Frontend Component Patterns?

因为您只需安装一次,就能搭配任何模型使用。Frontend Component Patterns 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Frontend Component Patterns?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/korallis/Droidz/tree/main/droidz_installer/payloads/claude/default/skills/frontend-component-patterns。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Frontend Component Patterns?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Frontend Component Patterns 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Frontend Component Patterns 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Frontend Component Patterns AI 技能免费吗?

korallis 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇