微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🧩

构建可扩展的 React 组件架构

Frontend Composition Patterns · v1.0.0
入口已确认,内容待校验 文件树里有 SKILL.md,但正文还没采回,frontmatter 未核对。
开发 安全 S 级 作者 wpank 公开目录收录
1.2k 下载 0 安装 3.9k 收藏 13 浏览

简介

React 组件组合模式,通过显式变体与上下文解耦状态与 UI,消除布尔属性泛滥,构建高可维护性的可复用组件库。

原始描述

Build flexible React components using compound components, context providers, and explicit variants to avoid boolean prop proliferation and improve scalability.

通过你的 Agent 添加

安装目录:frontend-composition-patterns/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/frontend-composition-patterns/
Codex CLI~/.codex/skills/frontend-composition-patterns/
DeepSeek Harness~/.agents/skills/frontend-composition-patterns/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心概述

本技能提供一套经过工程验证的 React 组合模式,旨在解决大型组件库中常见的布尔属性泛滥(boolean prop proliferation)问题——每个布尔属性翻倍可能的状态空间,导致组件难以预测和维护。

核心用法

技能围绕六大模式展开:

  1. 复合组件(Compound Components):通过共享 Context 将复杂组件拆分为可组合的子组件,如 Composer.Provider、Composer.Input、Composer.Submit,消费者按需装配。

  2. 通用上下文接口:定义 state/actions/meta 三层契约,使同一套 UI 可接入本地状态、全局状态或同步状态等不同实现,实现状态与 UI 的完全解耦。

  3. 显式变体:用命名组件替代布尔模式,如 <ThreadComposer />、<EditComposer /> 取代 isThread、isEditing 属性,意图自文档化。

  4. 状态提升(Lifted State):通过 Provider 边界而非视觉嵌套共享状态,使对话框预览、操作按钮等视觉层级外的组件也能访问和操作状态。

  5. 子组件优于 Render Props:用 children 组合结构,仅对数据传递保留 render props。

  6. 实现解耦:UI 组件只依赖接口,不感知状态来源(Redux、Zustand、本地 useState 等)。

显著优点

  • 类型安全:TypeScript 接口驱动,Context 值有完整类型约束
  • 可测试性:状态逻辑与渲染分离,便于独立测试
  • 可扩展性:新增变体只需新增 Provider,不修改现有组件
  • 团队协作:显式 API 减少沟通成本,代码即文档

潜在局限

  • 学习曲线:开发者需适应 Context 心智模型,避免滥用
  • 性能考量:高频更新场景需配合 useMemo/useCallback 或状态库优化
  • 嵌套深度:过度拆分可能导致组件树冗长

适合人群

  • 构建设计系统或组件库的前端工程师
  • 维护大型 React 应用、需重构「属性地狱」组件的开发者
  • 追求显式 API 设计、厌恶隐式约定的团队

常规风险

  • Context 更新导致不必要重渲染(需配合 React.memo 或 selector 模式)
  • 忘记提供默认值导致运行时 null 错误
  • 过度工程化:简单场景无需全套模式,权衡使用

来源可信度

模式源自 Vercel Engineering 工程实践,属于行业头部团队的架构经验沉淀,经大规模生产环境验证。

技能正文


name: react-composition-patterns model: standard

React Composition Patterns

Build flexible, maintainable React components using compound components, context providers, and explicit variants. Avoid boolean prop proliferation.

WHAT

Composition patterns that scale:

  • Compound components with shared context
  • State/actions/meta context interface for dependency injection
  • Explicit variant components over boolean props
  • Lifted state in provider components
  • Children composition over render props

WHEN

  • Refactoring components with many boolean props
  • Building reusable component libraries
  • Designing flexible component APIs
  • Creating compound components (Card, Dialog, Form, etc.)
  • Components need shared state across sibling elements

KEYWORDS

composition, compound components, context, provider, boolean props, variants, react patterns, component architecture, render props, children

Source: Vercel Engineering

Installation

OpenClaw / Moltbot / Clawbot

npx clawhub@latest install composition-patterns

Core Principle

Avoid boolean prop proliferation. Each boolean doubles possible states.

// BAD: 4 booleans = 16 possible states
<Composer isThread isDMThread isEditing isForwarding />

// GOOD: Explicit variants, clear intent
<ThreadComposer channelId="abc" />
<EditComposer messageId="xyz" />

Pattern 1: Compound Components

Structure complex components with shared context. Consumers compose what they need.

const ComposerContext = createContext<ComposerContextValue | null>(null)

// Provider handles state
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
  return (
    <ComposerContext value={{ state, actions, meta }}>
      {children}
    </ComposerContext>
  )
}

// Subcomponents access context
function ComposerInput() {
  const { state, actions: { update }, meta: { inputRef } } = use(ComposerContext)
  return (
    <TextInput
      ref={inputRef}
      value={state.input}
      onChangeText={(text) => update(s => ({ ...s, input: text }))}
    />
  )
}

function ComposerSubmit() {
  const { actions: { submit } } = use(ComposerContext)
  return <Button onPress={submit}>Send</Button>
}

// Export as namespace
const Composer = {
  Provider: ComposerProvider,
  Frame: ComposerFrame,
  Input: ComposerInput,
  Submit: ComposerSubmit,
  Header: ComposerHeader,
  Footer: ComposerFooter,
}

Usage:

<Composer.Provider state={state} actions={actions} meta={meta}>
  <Composer.Frame>
    <Composer.Header />
    <Composer.Input />
    <Composer.Footer>
      <Composer.Formatting />
      <Composer.Submit />
    </Composer.Footer>
  </Composer.Frame>
</Composer.Provider>

Pattern 2: Generic Context Interface

Define a contract any provider can implement: state, actions, meta.

interface ComposerState {
  input: string
  attachments: Attachment[]
  isSubmitting: boolean
}

interface ComposerActions {
  update: (updater: (state: ComposerState) => ComposerState) => void
  submit: () => void
}

interface ComposerMeta {
  inputRef: React.RefObject<TextInput>
}

interface ComposerContextValue {
  state: ComposerState
  actions: ComposerActions
  meta: ComposerMeta
}

Same UI, different providers:

// Local state provider
function ForwardMessageProvider({ children }) {
  const [state, setState] = useState(initialState)
  return (
    <ComposerContext value={{
      state,
      actions: { update: setState, submit: useForwardMessage() },
      meta: { inputRef: useRef(null) },
    }}>
      {children}
    </ComposerContext>
  )
}

// Global synced state provider  
function ChannelProvider({ channelId, children }) {
  const { state, update, submit } = useGlobalChannel(channelId)
  return (
    <ComposerContext value={{
      state,
      actions: { update, submit },
      meta: { inputRef: useRef(null) },
    }}>
      {children}
    </ComposerContext>
  )
}

Both work with the same <Composer.Input /> component.


Pattern 3: Explicit Variants

Create named components for each use case instead of boolean modes.

// BAD: What does this render?
<Composer
  isThread
  isEditing={false}
  channelId="abc"
  showAttachments
/>

// GOOD: Self-documenting
<ThreadComposer channelId="abc" />

Implementation:

function ThreadComposer({ channelId }: { channelId: string }) {
  return (
    <ThreadProvider channelId={channelId}>
      <Composer.Frame>
        <Composer.Input />
        <AlsoSendToChannelField channelId={channelId} />
        <Composer.Footer>
          <Composer.Formatting />
          <Composer.Submit />
        </Composer.Footer>
      </Composer.Frame>
    </ThreadProvider>
  )
}

function EditComposer({ messageId }: { messageId: string }) {
  return (
    <EditProvider messageId={messageId}>
      <Composer.Frame>
        <Composer.Input />
        <Composer.Footer>
          <Composer.CancelEdit />
          <Composer.SaveEdit />
        </Composer.Footer>
      </Composer.Frame>
    </EditProvider>
  )
}

Pattern 4: Lifted State

Components outside the visual hierarchy can access state via provider.

function ForwardMessageDialog() {
  return (
    <ForwardMessageProvider>
      <Dialog>
        {/* Composer UI */}
        <Composer.Frame>
          <Composer.Input placeholder="Add a message" />
          <Composer.Footer>
            <Composer.Formatting />
          </Composer.Footer>
        </Composer.Frame>

        {/* Preview OUTSIDE composer but reads its state */}
        <MessagePreview />

        {/* Actions OUTSIDE composer but can submit */}
        <DialogActions>
          <CancelButton />
          <ForwardButton />
        </DialogActions>
      </Dialog>
    </ForwardMessageProvider>
  )
}

// Can access context despite being outside Composer.Frame
function ForwardButton() {
  const { actions: { submit } } = use(ComposerContext)
  return <Button onPress={submit}>Forward</Button>
}

function MessagePreview() {
  const { state } = use(ComposerContext)
  return <Preview message={state.input} attachments={state.attachments} />
}

Key insight: Provider boundary matters, not visual nesting.


Pattern 5: Children Over Render Props

Use children for composition, render props only when passing data.

// BAD: Render props for structure
<Composer
  renderHeader={() => <CustomHeader />}
  renderFooter={() => <Formatting />}
  renderActions={() => <Submit />}
/>

// GOOD: Children for structure
<Composer.Frame>
  <CustomHeader />
  <Composer.Input />
  <Composer.Footer>
    <Formatting />
    <Submit />
  </Composer.Footer>
</Composer.Frame>

When render props ARE appropriate:

// Passing data to children
<List
  data={items}
  renderItem={({ item, index }) => <Item item={item} index={index} />}
/>

Pattern 6: Decouple State from UI

Only the provider knows how state is managed. UI consumes the interface.

// BAD: UI coupled to state implementation
function ChannelComposer({ channelId }) {
  const state = useGlobalChannelState(channelId)  // Knows about global state
  const { submit } = useChannelSync(channelId)    // Knows about sync
  
  return <Composer.Input value={state.input} onChange={...} />
}

// GOOD: State isolated in provider
function ChannelProvider({ channelId, children }) {
  const { state, update, submit } = useGlobalChannel(channelId)
  
  return (
    <Composer.Provider
      state={state}
      actions={{ update, submit }}
      meta={{ inputRef: useRef(null) }}
    >
      {children}
    </Composer.Provider>
  )
}

// UI only knows the interface
function ChannelComposer() {
  return (
    <Composer.Frame>
      <Composer.Input />  {/* Works with any provider */}
      <Composer.Submit />
    </Composer.Frame>
  )
}

Quick Reference

Anti-Pattern Solution
Boolean props Explicit variant components
Render props for structure Children composition
State in component Lift to provider
Coupled to state impl Generic context interface
Many conditional renders Compose pieces explicitly

Files

  • rules/architecture-avoid-boolean-props.md - Detailed boolean prop guidance
  • rules/architecture-compound-components.md - Compound component pattern
  • rules/state-context-interface.md - Context interface design
  • rules/state-decouple-implementation.md - State isolation
  • rules/state-lift-state.md - Provider pattern
  • rules/patterns-explicit-variants.md - Variant components
  • rules/patterns-children-over-render-props.md - Composition over callbacks

NEVER

  • Add boolean props to customize behavior (use composition)
  • Create components with more than 2-3 boolean mode props
  • Couple UI components to specific state implementations
  • Use render props when children would work
  • Trap state inside components when siblings need access

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

reactcomposition-patternscompound-componentscontext-apicomponent-architecturetypescriptdesign-systemsstate-management

同类 Skill