[英]How to export compound component in react js
I am trying to get my hands on compound component pattern in ReactJS.我正在尝试了解 ReactJS 中的复合组件模式。 And all is good but I am not able to export the component the way I want.
一切都很好,但我无法以我想要的方式导出组件。
I have created one basic Table (Data Grid), which has many component like header, row, column, search, pagination etc.我创建了一个基本表(数据网格),它有许多组件,如 header、行、列、搜索、分页等。
And I want the end user to import this Table in this way.我希望最终用户以这种方式导入此表。
import Table from './Table'
const DataGrid = () => {
return (
<Table>
<Table.Title></Table.Title>
<Table.Header>
<Table.Row></Table.Row>
</Table.Header>
<Table.Body>
<Table.Row></Table.Row>
</Table.Body>
</Table>
)
}
Now in component folder, I have one index.js file where I am trying to import all component and then trying to export it in a object现在在组件文件夹中,我有一个 index.js 文件,我正在尝试导入所有组件,然后尝试将其导出到 object
import {Table} from './Table'
import {Title} from './Title'
import {Header} from './Header'
import {Body} from './Body'
Now what should I do to export in a way I want.现在我应该怎么做才能以我想要的方式导出。 Tried many solutions, but nothing is working.
尝试了许多解决方案,但没有任何效果。
You need to import everything in index
file and prepare a new object and export it:您需要导入
index
文件中的所有内容并准备一个新的 object 并将其导出:
index.js: index.js:
import { Table } from "./Table"; // this imports from Table.jsx file
import { Title } from "./Title";
import { Body } from "./Body";
import { Header } from "./Header";
import { Row } from "./Row";
const all = Table; // <-- Here: this (all) is the new object.
// We can name it whatever we want as it is going to be a default export
all.Title = Title;
all.Body = Body;
all.Header = Header;
all.Row = Row;
export default all;
Now, you can use it like shown below:现在,您可以使用它,如下所示:
DataGrid.jsx:数据网格.jsx:
import Table from "./Table"; // this imports from index.js file under "Table" folder
const DataGrid = () => {
return (
<Table>
<Table.Title></Table.Title>
<Table.Header>
<Table.Row></Table.Row>
</Table.Header>
<Table.Body>
<Table.Row></Table.Row>
</Table.Body>
</Table>
);
};
This answer assumes that you have components under directories like below.此答案假设您在如下目录下有组件。 Make sure to change the paths when importing if you have a different one.
如果您有不同的路径,请确保在导入时更改路径。
src/
Table/
Body.jsx
Header.jsx
index.js
Row.jsx
Table.jsx
Title.jsx
DataGrid.jsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.