> For the complete documentation index, see [llms.txt](https://zg-zhang.gitbook.io/note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zg-zhang.gitbook.io/note/react/offical-website/main-concepts/composition-vs-inheritance.md).

# 组合 vs 继承

* React 有十分强大的组合模式，我们推荐使用组合而非继承来实现组件间的代码重用

## 包含关系

* 有些组件无法提前知晓它们子组件的具体内容。比如说侧边栏 sidebar 和 对话框 Dialog 等展现通用容器的组件中特别容易遇到这种情况

  \`\`\`jsx harmony

function FancyBorder(props) { return (  {props.children} ) }

````
* 这使得别的组件可以通过 JSX 嵌套，将任意组件作为子组件传递给他们

* 少数情况下，你可能需要一个组件中预留出几个 洞，这种情况下，我们可以不适用 children 而是自行约定：将所需的内容传入 props 并使用相应的 prop
```jsx harmony

function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
        {props.left}
      </div>
      <div className="SplitPane-right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}
````

* 这里面的 Contacts 和 Chat 之类的 React 元素本质就是对象，所以你可以把它们当作 props，你可以将任何东西作为 props 进行传递


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zg-zhang.gitbook.io/note/react/offical-website/main-concepts/composition-vs-inheritance.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
