【问题标题】:Named exports with HOCs使用 HOC 命名的导出
【发布时间】:2019-02-18 16:29:07
【问题描述】:

问题

假设我有一个 SFC(我正在使用 TypeScript)并将其导出为:

export const AppShell: React.SFC<Props> = (props: Props) => (
  ...
)

一切都好。但是现在在我导出我的组件之前,我想用像 withStyles 这样的 HOC 来包装它,来自 MaterialUI。现在我想做类似的事情:

const AppShell: React.SFC<Props> = (props: Props) => (
 ...
)

并将其导出为:

export const AppShell = withStyles(styles)<Props>(AppShell);

当然这会导致错误:

[ts] Cannot redeclare block-scoped variable 'AppShell'.

权衡的解决方案

据我所知,我现在有两个选择:

1) 使用默认导出:

export default withStyles(styles)<Props>(AppShell);

因为我不喜欢默认导出,因为它们有很多 disadvantages,我不同意那个解决方案。

2) 在包装之前为我的组件使用“Raw”之类的前缀:

const RawAppShell: React.SFC<Props> = (props: Props) => (
 ...
)

像这样导出:

export const AppShell = withStyles(styles)<Props>(RawAppShell);

我更喜欢这种方法,但要权衡添加这个前缀。

其他解决方案

您如何在项目中处理这个问题?是否已经有最佳实践解决方案?对我来说,我的组件有一个命名导出非常重要,因此我根本无法接受具有默认导出的解决方案。

提前谢谢你。

【问题讨论】:

  • 装饰器语法呢? @withStylesexport const AppShell... 之前的一行。我没有尝试使用 Typescript,但在常规 js 中可以正常工作。虽然需要 babel 插件来转译这种语法。
  • @EgorStambakio 很遗憾没有:github.com/Microsoft/TypeScript/issues/4881

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

只需在一个语句中完成:

export const AppShell: React.SFC<Props> = withStyles(styles)<Props>((props: Props) => (
  …
));

【讨论】:

  • 我也想过这个解决方案,但我认为如果您需要多个 HOC,这最终会变得一团糟。另外,我计划在我的应用程序中使用 Redux,然后我会使用 Redux 的 compose(redux.js.org/api/compose) 功能。所以我认为这个解决方案不适合我。
  • 这只是意味着您可以将 HOC 组合到一个 HOC,然后在箭头函数上使用它?
  • 我觉得这会很混乱。
  • 要么将 compose 结果放入临时变量中,要么使用缩进(每个 compose 参数在其自己的行中)
  • 您的项目中也这样做?但我想我会试试这个,我会看看感觉如何。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多