首页 > 解决方案 > 在道具对象之外传递“道具”是一种反模式吗?

问题描述

我正在使用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 => {...}

我应该坚持使用常规道具吗?或者如果我像这样传递我的额外道具可以吗?

会不会带来不好的表现?以后它会咬我,给我带来难以追踪的错误吗?

谢谢

标签: javascriptreactjsdesign-patternsfunctional-programming

解决方案


两种方法有细微差别。

// 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()

推荐阅读