将react-bootstrap Button与react-router和typescript一起使用时出现类型问题

问题描述 投票:0回答:1

我创建了一个简单的反应引导卡组件,如下所示:

<Card className={` ${styles.stretchCard}`}>
  <Card.Body className='d-flex flex-column'>
    <Card.Title>{post.title}</Card.Title>
    <Card.Text className='m-0'><span className={styles.dataTitle}>Author: </span>{post.author}</Card.Text>
    <Card.Text ><span className={styles.dataTitle}>Published: </span>{post.publishedDate}</Card.Text>
    <Card.Text>{post.shortDescription}</Card.Text>
    <Button
      as={Link}
      to={`post/${post.id}`}
      className='align-self-start mt-auto'
    >
      Read more
    </Button>
  </Card.Body>
</Card>

该组件使用了 boostrap

Button
,其中传递了
as
属性,它是一个
react-router
Link
组件。一切正常,但编译代码后出现以下错误:

类型“ForwardRefExoticComponent”不可分配给类型“(ForwardRefExoticComponent & keyof IntrinsicElements) |不明确的'。 类型“ForwardRefExoticComponent”不可分配给类型“ForwardRefExoticComponent &“symbol””。 类型“ForwardRefExoticComponent”不可分配给类型““symbol””。 18 | 18 发布:{post.publishedDate} 19 | 19 {post.shortDescription} 20 |

我想知道我是否可以将

Link
项目投射为特定类型 - 如果可以的话它应该是什么样子,因为这是我无法弄清楚的。我真的很想对整个项目进行类型检查,所以我不想强制转换为“任何”。

typescript react-router react-bootstrap
1个回答
0
投票

这可能会晚一些,但是在将

link
组件传递给
Button
组件时将其转换为 React.ComponentClass 似乎可以解决您所描述的问题。

将其放在这里以供将来参考。

import { Link, LinkProps } from "react-router-dom";
import { Button } from "react-bootstrap";

type CustomBootstrapLinkType = React.ComponentClass<LinkProps> & keyof JSX.IntrinsicElements

<Button
  variant="link"
  as={
    Link as unknown as CustomBootstrapLinkType
  }
  to={`post/${post.id}`}
>
    view more &gt;
</Button>
© www.soinside.com 2019 - 2024. All rights reserved.