javascript - 在道具对象之外传递“道具”是一种反模式吗?
问题描述
我正在使用AntD <Table />
组件。当我生成列时,我想将自定义道具传递给我的单元格,这些单元格不属于我提供表格的数据。它可能是主题、调色板、布局设置等。
每列都由一个对象表示并具有一个render
方法。AntD 遍历行和列,并通过record
给定的 渲染该行的cell
。
{
... // keys like `key`, `title`, `dataIndex` ...
render: (record) => {...}
}
而不是像这样直接将我的额外道具传递给组件本身:
{
... // keys like `key`, `title`, `dataIndex` ...
render: (record) => <MyCell {...record} extraProp={extraProp} extraProp2={extraProp2} />
}
我养成了这样写的习惯:
{
... // keys like `key`, `title`, `dataIndex` ...
render: MyCell(extraProp, extraProp2)
}
其中 MyCell 定义为:
const MyCell = (extrProp, extraProp2) => props => {...}
我应该坚持使用常规道具吗?或者如果我像这样传递我的额外道具可以吗?
会不会带来不好的表现?以后它会咬我,给我带来难以追踪的错误吗?
谢谢
解决方案
两种方法有细微差别。
// 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.
主要区别在于额外的 props ( extraProp-x
),在使用函数时是动态的,而在使用函数组件时是静态的:
// 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)
最常见的方式是渲染功能组件,让父级处理 props 的变化。
// 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()} />;
总之,这不是“反模式”,这取决于您的意图,有时会使用“返回组件的函数”,但我怀疑情况是否如此。
请注意,您可以将默认道具添加到
generateMyCell
:
const generateMyCell = (extrProp = def1, extraProp2 = def2) =>
props => {...}
// Call it with props when they need to change.
generateMyCell()
推荐阅读
- sql-server - 在 case 语句中无法将 varchar 转换为二进制
- saml - 签署 SAML 响应和断言之间的 OpenAM 关系
- jquery - 警告:组件渲染函数中可能存在无限更新循环
- apache-spark - Spark客户端内存配置
- elasticsearch - Logstash 错误:拒绝对 [db] 的映射更新,因为最终映射将有超过 1 种类型:[meeting_invities, meetingroom"}}}}
- python - 在多个处理器上运行外部应用程序
- ggplot2 - 如何在 ggplot 中使用 colorRamp 绘制饼图?
- flutter - Flutter CameraException:CameraException(错误 -11803,AVFoundationErrorDomain)
- python - 在 TensorFlow 2.0 中,如何将 TFRecord 数据提供给 keras 模型?
- android - 如何停止在输入法中触发“updateCursor”事件?