简体   繁体   English

渲染React组件的通用方法取决于两个道具

[英]Generic method to render React component depends on two props

I've got a component that gets two props, function and node(or string with label text), depends on these props I render the icon with some label. 我有一个组件,它有两个道具,函数和节点(或带有标签文本的字符串),取决于这些道具,我用一些标签渲染图标。 In future, I'm going to add more button and want to create the generic method that rendered this icon more flexible. 将来,我将添加更多按钮,并希望创建使该图标更加灵活的通用方法。 So how to create such generic method for that? 那么如何为此创建通用方法呢?

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'}>

Maybe do something like: 也许做类似的事情:

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} />;
  }
}

You even the possiblity to throw those EXPORT_EXCEL and REFRESH into array. 您甚至可以将那些EXPORT_EXCEL和REFRESH放入数组。 Instead of having them loose put them in an array like so: 不要让它们松散地将它们放在数组中,如下所示:

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 */ } 
  },
];

And then loop through to create the Wrapper. 然后循环遍历以创建包装器。

But then it's really up to you and your preferences and app's requirements 但这实际上取决于您以及您的喜好和应用程序的要求

The entire idea behind React is to be able to create a unique component for every kind of usage. React背后的整个想法是能够为每种使用创建一个独特的组件。 That is the entire philosophy behind React composability. 这就是React可组合性背后的全部理念。 Don't understand why would you want to wrap it. 不明白为什么要包装它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM