九. React的组合 VS 继承(Composition vs Inheritance)

React 拥有一个强大的组合模型,官网建议使用组合而不是继承以实现代码的重用。

一. 包含

一些组件在设计前无法获知自己要什么子组件,尤其在Sidebar和Dialog等通用"容器"中比较常见。
对于这种组件使用特别的children props来直接传递子元素到他们的输出中:

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

这时其他组件就可以通过嵌套JSX传递任意子组件:

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

有时候也可以使用占位符而不是children。

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 />
      } />
  );
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容