【问题标题】:Using a Link component with ListItem and Typescript使用带有 ListItem 和 Typescript 的 Link 组件
【发布时间】:2019-04-21 21:23:44
【问题描述】:

我正在使用material-ui v3.5.1

我想让 ListItem 像这样使用 Link 组件:

<ListItem component={Link} to="/some/path">
  <ListItemText primary="Text" />
</ListItem>

但是 Typescript 用一个冗长的错误消息向我打招呼(“组件”这个词在 VSCode 中突出显示),在底部它说:

The type "typeof Link" cannot be assigned to the type "ComponentClass<ListItemProps, any>"

Property 'to' is missing in type 'ListItemProps' but required in type 'Readonly'. [2322]

有没有一种解决方法可以让这些东西与 Typescript 一起使用?

谢谢!

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    目前这是我们类型声明的一个限制(直到我们转向通用道具)。作为临时解决方法,您可以将链接提取到另一个组件中,例如

    function SomePathLink(props: ButtonBaseProps) {
      return <Link to="/some/path" {...props} />
    }
    
    <ListItem component={SomePathLink}>
      <ListItemText primary="Text" />
    </ListItem>
    

    文档中有更详细的解释:https://material-ui.com/demos/buttons/#third-party-routing-library

    【讨论】:

    • 谢谢,成功了。我不得不将 ButtonBaseProps 转换为 LinkProps: const SomePathLink = (eventId: string) => (props: ButtonBaseProps) => { return /events/${eventId}} {...props as LinkProps} /> }
    • 错误是什么?您不应该强制转换它,因为这可能会导致运行时问题。
    • 如果我不强制转换:“{ action?: ((actions: ButtonBaseActions) => void) | undefined; buttonRef?: ((instance: any) => void) | RefObject | null | undefined; centerRipple?: boolean | undefined; component?: string | ... 2 more ... | undefined; ... 274 more ...; to: string; }" 不能分配给“只读”类型。属性“innerRef”不是补偿。类型“((instance: any) => void) | RefObject | null | undefined”不能分配给类型“((node: HTMLAnchorElement | null) => void) | undefined”。 “null”不能分配给“((node: HTMLAnchorElement | null) => void) | undefined”。 [2322]"
    • 这几乎可以工作。我收到此错误:[...] 属性“innerRef”的类型不兼容。输入'((实例:任何)=> void)|参考对象 |空 | undefined' 不可分配给类型 '((node: HTMLAnchorElement | null) => void) |不明确的'。类型 'null' 不能分配给类型 '((node: HTMLAnchorElement | null) => void) |未定义'。
    • @Arkanoid 这应该在下一个版本中修复。您可以检查主版本或专门申请 github.com/mui-org/material-ui/pull/14333 看看是否有帮助
    猜你喜欢
    • 2016-05-27
    • 2017-10-03
    • 1970-01-01
    • 2019-02-23
    • 2023-03-20
    • 2019-11-29
    • 2019-08-20
    • 2016-10-05
    • 2021-02-04
    相关资源
    最近更新 更多