【发布时间】: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);
我更喜欢这种方法,但要权衡添加这个前缀。
其他解决方案
您如何在项目中处理这个问题?是否已经有最佳实践解决方案?对我来说,我的组件有一个命名导出非常重要,因此我根本无法接受具有默认导出的解决方案。
提前谢谢你。
【问题讨论】:
-
装饰器语法呢?
@withStyles在export const AppShell...之前的一行。我没有尝试使用 Typescript,但在常规 js 中可以正常工作。虽然需要 babel 插件来转译这种语法。 -
@EgorStambakio 很遗憾没有:github.com/Microsoft/TypeScript/issues/4881
标签: javascript reactjs typescript ecmascript-6