composition-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseComposition Patterns
组合模式
Part of Agent Skills™ by googleadsagent.ai™
Description
描述
Composition Patterns teaches agents to build flexible, maintainable React components using compound components, state lifting, internal composition, and the elimination of boolean prop proliferation. These patterns replace rigid, prop-heavy APIs with composable interfaces that scale gracefully as requirements evolve.
The most common agent mistake in React is building monolithic components with dozens of boolean props: , , , , , . Each boolean doubles the component's state space, creating an exponential testing surface and making the component impossible to extend without modifying its internals. Composition patterns replace these booleans with structural composition, where the consumer assembles the component from smaller pieces.
showHeadershowFooterisCompactisLoadinghasSearchenableDarkModeThis skill addresses four complementary patterns: compound components for related UI families, state lifting for shared cross-component state, internal composition for encapsulated sub-rendering, and render delegation for maximum consumer flexibility. Applied together, these patterns produce components that are simple to use, powerful to customize, and trivial to test.
组合模式指导Agent使用复合组件、状态提升、内部组合以及消除布尔属性泛滥的方式,构建灵活且可维护的React组件。这些模式将僵化、依赖大量属性的API替换为可组合的接口,能随着需求演变优雅地扩展。
Agent在React开发中最常见的错误是构建包含数十个布尔属性的单体组件:、、、、、。每个布尔属性都会使组件的状态空间翻倍,导致测试范围呈指数级增长,并且不修改组件内部就无法扩展。组合模式用结构化组合替代这些布尔属性,由使用者将组件拆分为更小的部分进行组装。
showHeadershowFooterisCompactisLoadinghasSearchenableDarkMode本技能涵盖四种互补模式:用于相关UI系列的复合组件、用于跨组件共享状态的状态提升、用于封装子渲染的内部组合,以及实现最大使用者灵活性的渲染委托。结合使用这些模式,能够生成易于使用、高度可定制且测试简单的组件。
Use When
使用场景
- A component has more than 3 boolean configuration props
- Related components need to share implicit state (tabs, accordions, selects)
- The consumer needs to control layout or ordering of sub-elements
- A component needs to support use cases not anticipated at design time
- Refactoring a "god component" into composable pieces
- Building a component library or design system
- 组件包含3个以上用于配置的布尔属性
- 相关组件需要共享隐式状态(标签页、折叠面板、选择器)
- 使用者需要控制子元素的布局或顺序
- 组件需要支持设计时未预料到的使用场景
- 将“上帝组件”重构为可组合的模块
- 构建组件库或设计系统
How It Works
工作原理
mermaid
graph TD
A[Component Design Request] --> B{Pattern Selection}
B --> C[Compound: Related UI Family]
B --> D[State Lifting: Shared State]
B --> E[Internal Composition: Sub-render]
B --> F[Render Delegation: Consumer Control]
C --> G[Parent provides context]
G --> H[Children consume context]
D --> I[State lives in nearest common ancestor]
E --> J[Component composes internally]
F --> K[Consumer passes render function]The agent selects the appropriate pattern based on the relationship between components, the degree of consumer control needed, and the complexity of shared state.
mermaid
graph TD
A[Component Design Request] --> B{Pattern Selection}
B --> C[Compound: Related UI Family]
B --> D[State Lifting: Shared State]
B --> E[Internal Composition: Sub-render]
B --> F[Render Delegation: Consumer Control]
C --> G[Parent provides context]
G --> H[Children consume context]
D --> I[State lives in nearest common ancestor]
E --> J[Component composes internally]
F --> K[Consumer passes render function]Agent会根据组件之间的关系、所需的使用者控制程度以及共享状态的复杂度,选择合适的模式。
Implementation
实现
Compound Components
复合组件
tsx
const TabsContext = createContext<TabsState | null>(null);
function Tabs({ defaultValue, children }: TabsProps) {
const [active, setActive] = useState(defaultValue);
return (
<TabsContext.Provider value={{ active, setActive }}>
<div role="tablist">{children}</div>
</TabsContext.Provider>
);
}
function Tab({ value, children }: TabProps) {
const { active, setActive } = useContext(TabsContext)!;
return (
<button
role="tab"
aria-selected={active === value}
onClick={() => setActive(value)}
>
{children}
</button>
);
}
function TabPanel({ value, children }: TabPanelProps) {
const { active } = useContext(TabsContext)!;
if (active !== value) return null;
return <div role="tabpanel">{children}</div>;
}
Tabs.Tab = Tab;
Tabs.Panel = TabPanel;
// Usage: consumer controls structure
<Tabs defaultValue="a">
<Tabs.Tab value="a">Tab A</Tabs.Tab>
<Tabs.Tab value="b">Tab B</Tabs.Tab>
<Tabs.Panel value="a">Content A</Tabs.Panel>
<Tabs.Panel value="b">Content B</Tabs.Panel>
</Tabs>tsx
const TabsContext = createContext<TabsState | null>(null);
function Tabs({ defaultValue, children }: TabsProps) {
const [active, setActive] = useState(defaultValue);
return (
<TabsContext.Provider value={{ active, setActive }}>
<div role="tablist">{children}</div>
</TabsContext.Provider>
);
}
function Tab({ value, children }: TabProps) {
const { active, setActive } = useContext(TabsContext)!;
return (
<button
role="tab"
aria-selected={active === value}
onClick={() => setActive(value)}
>
{children}
</button>
);
}
function TabPanel({ value, children }: TabPanelProps) {
const { active } = useContext(TabsContext)!;
if (active !== value) return null;
return <div role="tabpanel">{children}</div>;
}
Tabs.Tab = Tab;
Tabs.Panel = TabPanel;
// Usage: consumer controls structure
<Tabs defaultValue="a">
<Tabs.Tab value="a">Tab A</Tabs.Tab>
<Tabs.Tab value="b">Tab B</Tabs.Tab>
<Tabs.Panel value="a">Content A</Tabs.Panel>
<Tabs.Panel value="b">Content B</Tabs.Panel>
</Tabs>Eliminating Boolean Props
消除布尔属性泛滥
tsx
// BAD: Boolean prop explosion
<Card
showHeader={true}
showFooter={false}
isCompact={true}
hasAvatar={true}
showActions={true}
/>
// GOOD: Compositional API
<Card compact>
<Card.Header>
<Avatar src={user.avatar} />
<Card.Title>{user.name}</Card.Title>
</Card.Header>
<Card.Body>{content}</Card.Body>
<Card.Actions>
<Button>Edit</Button>
<Button>Delete</Button>
</Card.Actions>
</Card>tsx
// BAD: Boolean prop explosion
<Card
showHeader={true}
showFooter={false}
isCompact={true}
hasAvatar={true}
showActions={true}
/>
// GOOD: Compositional API
<Card compact>
<Card.Header>
<Avatar src={user.avatar} />
<Card.Title>{user.name}</Card.Title>
</Card.Header>
<Card.Body>{content}</Card.Body>
<Card.Actions>
<Button>Edit</Button>
<Button>Delete</Button>
</Card.Actions>
</Card>Best Practices
最佳实践
- Use compound components when sub-elements share implicit state
- Expose composable APIs instead of adding boolean flags for new features
- Keep context providers narrow—one context per concern, not one mega-context
- Provide sensible defaults so simple use cases remain simple
- Document the compositional API with usage examples, not just prop tables
- Use TypeScript discriminated unions instead of boolean prop combinations
- 当子元素共享隐式状态时,使用复合组件
- 暴露可组合API,而非为新功能添加布尔标记
- 保持上下文提供者的范围狭窄——每个关注点对应一个上下文,而非一个巨型上下文
- 提供合理的默认值,确保简单使用场景依然简便
- 用使用示例而非仅属性表来记录可组合API
- 使用TypeScript区分联合类型替代布尔属性组合
Platform Compatibility
平台兼容性
| Platform | Support | Notes |
|---|---|---|
| Cursor | Full | Component generation + refactoring |
| VS Code | Full | TypeScript-aware refactoring |
| Windsurf | Full | React pattern recognition |
| Claude Code | Full | Component design guidance |
| Cline | Full | Pattern-based generation |
| aider | Partial | Limited compositional awareness |
| 平台 | 支持程度 | 说明 |
|---|---|---|
| Cursor | 完全支持 | 组件生成 + 重构 |
| VS Code | 完全支持 | 识别TypeScript的重构 |
| Windsurf | 完全支持 | React模式识别 |
| Claude Code | 完全支持 | 组件设计指导 |
| Cline | 完全支持 | 基于模式的生成 |
| aider | 部分支持 | 可组合性感知有限 |
Related Skills
相关技能
- React Best Practices
- View Transitions
- Web Design Guidelines
- Edge Rendering
- React最佳实践
- 视图过渡
- Web设计指南
- 边缘渲染
Keywords
关键词
compositioncompound-componentsreact-patternsstate-liftingboolean-propsrender-delegationdesign-systemcomposable-api© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
compositioncompound-componentsreact-patternsstate-liftingboolean-propsrender-delegationdesign-systemcomposable-api© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License