将“道具”传递到道具对象之外是否是反模式?

我正在使用AntD <Table />组件。当我生成列时,我想将自定义道具传递给不属于数据表的数据单元。可能是主题,调色板,布局设置等。

每列由一个对象表示,并具有render方法。 AntD遍历行和列,并传递要由给定record呈现的行的cell

{
   ... // keys like `key`,`title`,`dataIndex` ...
   render: (record) => {...}
}

不是像这样直接将我的额外道具传递给组件本身:

{
   ... // keys like `key`,`dataIndex` ...
   render: (record) => <MyCell {...record} extraProp={extraProp} extraProp2={extraProp2} />
}

我有写这样的习惯:

{
   ... // keys like `key`,`dataIndex` ...
   render: MyCell(extraProp,extraProp2)
}

其中MyCell定义为:

const MyCell = (extrProp,extraProp2) => props => {...}

我应该坚持使用常规道具吗?还是我通过这样的额外道具好吗?

会导致性能下降吗?将来会咬我,使我难以追踪的错误吗?

谢谢

vbsnowy 回答:将“道具”传递到道具对象之外是否是反模式?

两种方法略有不同。

// 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.

主要区别在于,额外的道具(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)

最常见的方法是渲染功能组件,然后让父级处理道具更改。

// 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()
本文链接:https://www.f2er.com/3161805.html

大家都在问