如何导出带有相关“子”组件的 React 组件

Bry*_*yan 5 reactjs

我见过一些库支持执行以下操作的功能

<Table>
    <Table.Row>This would replace importing a component called TableRow separately.</Table.Row>
</Table>
Run Code Online (Sandbox Code Playgroud)

不确定这是否是不好的做法,但想知道你是如何做到的。

小智 5

您可以通过将子组件添加到父组件对象并导出父组件来完成此操作。不完全是不好的做法,但它对保持组件的组织有很大帮助。

import React from 'react';

const Row = ({children}) => <span>{children}</span>;

const Table = ({children}) => <>{children}</>;

Table.Row = Row;

export default Table;
Run Code Online (Sandbox Code Playgroud)


Dre*_*ese 1

这是一种称为复合组件的设计模式。您可以将子组件设置为外部类的静态成员。

import React, { Component } from "react";
import PropTypes from "prop-types";

const Row = ({ children }) => <div>{children}</div>;

class Table extends Component {
  static Row = Row;

  render() {
    const { children, ...props } = this.props;
    return <div {...props}>{children}</div>;
  }
}

Table.propTypes = {
  children: PropTypes.arrayOf(
    PropTypes.shape({
      type: PropTypes.oneOf([Row])
    })
  )
};

export default Table;
Run Code Online (Sandbox Code Playgroud)

用法

import Table from "./Table";

...

<Table>
  <Table.Row>I'm a compound Row component!!</Table.Row>
  <Table.Row>I'm another compound Row component!!</Table.Row>
  <div>I'll throw a react proptype warning</div>
</Table>
Run Code Online (Sandbox Code Playgroud)

编辑复合组件

我们如何通过功能组件来实现这一点?

它几乎是相同的,但只是将复合组件作为属性添加到根组件。如果Table是一个功能组件,则将组件添加到Row其中,Table.Row = Row;。随着类组件在 React 中失宠,这是首选模式。

const Row = ({ children }) => <div>{children}</div>;

const Table = ({ children, ...props }) => (
  <div {...props}>{children}</div>
);

Table.Row = Row;

export default Table;
Run Code Online (Sandbox Code Playgroud)