材质UI <TableRow组件= {Link}> TypeScript错误TS2769

时间:2019-11-26 10:59:55

标签: reactjs typescript react-router material-ui react-router-dom

我正在使用Typescript和Material UI创建一个React SPA。我试图添加一个表,每行都是一个链接。该链接组件来自React Router。我的表格看起来与此类似(删除了大量代码以提供简化版本)。

<Table>
  {data.map((item, index) => {
    return (
      <TableRow component={Link} to="/example">
        <TableCell></TableCell>
      </TableRow>
</Table>

这在开发环境中有效,但是由于错误而无法构建项目:

TS2769: No overload matches this call.
  Overload 1 of 2, '(props: TableRowProps, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | Component<...> | null', gave the following error.
    Type 'typeof Link' is not assignable to type '"abbr" | "address" | "article" | "aside" | "b" | "bdi" | "bdo" | "big" | "blockquote" | "caption" | "cite" | "code" | "dd" | "del" | "details" | "dfn" | "div" | "dt" | "em" | "figcaption" | ... 45 more ... | undefined'.
      Type 'typeof Link' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLTableRowElement>, any>'.
        Types of parameters 'props' and 'props' are incompatible.
          Property 'to' is missing in type 'HTMLAttributes<HTMLTableRowElement>' but required in type 'Readonly<LinkProps<any>>'.
  Overload 2 of 2, '(props: PropsWithChildren<TableRowProps>, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | Component<...> | null', gave the following error.
    Type 'typeof Link' is not assignable to type '"abbr" | "address" | "article" | "aside" | "b" | "bdi" | "bdo" | "big" | "blockquote" | "caption" | "cite" | "code" | "dd" | "del" | "details" | "dfn" | "div" | "dt" | "em" | "figcaption" | ... 45 more ... | undefined'.
      Type 'typeof Link' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLTableRowElement>, any>'.

我很困惑如何解决这个问题。通过几次搜索,看来此问题仅存在于TypeScript中。

1 个答案:

答案 0 :(得分:1)

该错误基本上表明Link的属性与表行不兼容。

如果您希望表行具有链接的可点击性,则可以使用onClick react-router对象,例如,添加history处理程序。使用the useHistory hook

或者,如果您想生活在边缘,可以告诉TypeScript让演员一个人呆着

<TableRow component={Link as any} to="/example">

但是就类型安全性而言,您自然会自己一个人。