渲染 React 组件的通用方法依赖于两个 props



我有一个组件,它有两个道具,函数和节点(或带有标签文本的字符串(,取决于这些道具,我用一些标签渲染图标。将来,我将添加更多按钮,并希望创建使此图标更加灵活的泛型方法。那么如何为此创建这样的通用方法呢?

const Wrapper = ({onRefresh, onExportToExcel, actionsLabel}) => {
   return 
    {onRefresh && !!actionsLabel.refresh &&
                    <InlineIconButton name='refresh'  label={actionsLabel.refresh} onClick={onRefresh} icon={<Autorenew/>} aria-label="Refresh"/>}
    {onExportToExcel && !!actionsLabel.exportToExcel &&
                    <InlineIconButton name='exportToExcel' label={actionsLabel.exportToExcel} onClick={onExportToExcel} icon={<FileDownload/>} aria-label="ExportToExcel"/>}
}
<Wrapper onRefresh={()=> {}} onExportToExcel ={()=> {}} actionLabel={refresh: 'refresh', exportToExcel: 'export'}>

也许可以做这样的事情:

const EXPORT_EXCEL = { 
  key: "EXPORT_EXCEL", 
  label: "export",
  ariaLabel: "Export Excel",
  icon: <Autorenew/>,
  handler: params => { /* your function */ }
};
const REFRESH = { 
  key: "REFRESH", 
  label: "refresh",
  ariaLabel: "Refresh",
  icon: <FileDownload/>,
  handler: params => { /* your function */ } 
};
<Wrapper type={EXPORT_EXCEL} />;
const Wrapper = ({ type }) => {
      return <InlineIconButton name={type.key} label={type.label} onClick={type.handler} icon={type.icon} aria-label={type.ariaLabel ? type.ariaLabel : type.label} />;
  }
}

您甚至可以将这些EXPORT_EXCEL和刷新放入数组中。而不是让它们松散,将它们放在一个数组中,如下所示:

const BUTTONS = [
  { 
    key: "EXPORT_EXCEL", 
    label: "export",
    ariaLabel: "Export Excel",
    icon: <Autorenew/>,
    handler: params => { /* your function */ }
  },
  { 
    key: "REFRESH", 
    label: "refresh",
    ariaLabel: "Refresh",
    icon: <FileDownload/>,
    handler: params => { /* your function */ } 
  },
];

然后循环创建包装器。

但是,这实际上取决于您和您的偏好以及应用程序的要求

React 背后的整个想法是能够为每种用途创建一个独特的组件。这就是 React 可组合性背后的整个理念。不明白你为什么要包装它。

最新更新