I am using AntD <Table />
component. When I am generating the columns I want to pass custom props to my cells that are not part of the data I am feeding the table. It could be things like theme, color palette, layout setting etc..
Each column is represented by an object and has a render
method. AntD iterates over the rows and the columns and passes the record
of that row to be rendered by the given cell
.
{
... // keys like `key`, `title`, `dataIndex` ...
render: (record) => {...}
}
Instead of passing my extra props to the component itself directly like this:
{
... // keys like `key`, `title`, `dataIndex` ...
render: (record) => <MyCell {...record} extraProp={extraProp} extraProp2={extraProp2} />
}
I got in the habit of writing something like this:
{
... // keys like `key`, `title`, `dataIndex` ...
render: MyCell(extraProp, extraProp2)
}
Where MyCell is defined as:
const MyCell = (extrProp, extraProp2) => props => {...}
Should I stick to using regular props? Or is it fine if I pass my extra props like this?
Will it incur bad performance? Will it bite me in the future, giving me bugs hard to trace?
Thanks
Two approaches have a minor difference.
// It isn't a functional component,
// it's curried function which returns a functional component
const generateMyCell = (extrProp, extraProp2) => props => {...}
// ^ naming it MyCell is misleading.
The main difference is that the extra props ( extraProp-x
), are dynamic when using the function, and static when using the functional component:
// v The extra props are static, they won't change
render: record => (
<MyCell {...record} extraProp={extraProp} extraProp2={extraProp2} />
);
// v The developer shows intetation that props may change
render: generateMyCell(extraProp, extraProp2)
The most common way is rendering the functional component, and let the parent handle the props change.
// Most readable and common
const generateTableColumns = () => {
// Handle the props here.
const columns = [
{
render: (
<MyCell {...record} extraProp={extraProp} extraProp2={extraProp2} />
)
}
];
return columns;
};
// Usage
<Table columns={generateTableColumns()} />;
In conclusion, it is not an "Anti Pattern", it's a matter of what is your intents, there are occasions to use a "function that returns a component" but I doubt that it is the case.
Note that you can add default props to
generateMyCell
:
const generateMyCell = (extrProp = def1, extraProp2 = def2) =>
props => {...}
// Call it with props when they need to change.
generateMyCell()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.