ค้นหาเว็บไซต์

ปัญหาเกี่ยวกับชนิดข้อมูลเมื่อต้องใช้ปุ่ม react-bootstrap ร่วมกับ react-router และ typescript


ฉันได้สร้างคอมโพเนนต์การ์ด React Bootstrap แบบง่ายซึ่งมีลักษณะดังนี้:

<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 และมันเป็นคอมโพเนนต์ Link ของ react-router ทุกอย่างทำงานได้อย่างปกติดี แต่หลังจากคอมไพล์โค้ดฉันได้รับข้อผิดพลาดดังต่อไปนี้:

ประเภท 'ForwardRefExoticComponent' ไม่สามารถกำหนดค่าให้กับประเภท '(ForwardRefExoticComponent & keyof IntrinsicElements) | undefined' ได้ ประเภท 'ForwardRefExoticComponent' ไม่สามารถกำหนดค่าให้กับประเภท 'ForwardRefExoticComponent & "symbol"' ได้ ประเภท 'ForwardRefExoticComponent' ไม่สามารถกำหนดค่าให้กับประเภท '"symbol"' ได้ 18 | Published: {post.publishedDate} 19 | {post.shortDescription} 20 |

ฉันกำลังสงสัยว่าฉันจะสามารถแคสต์ไอเท็ม Link เป็นประเภทเฉพาะได้หรือไม่ - ถ้าได้มันควรจะหน้าตาเป็นอย่างไร เพราะนั่นคือสิ่งที่ฉันไม่สามารถหาคำตอบได้ ฉันอยากจะเก็บการตรวจสอบประเภทสำหรับทั้งโปรเจกต์ ดังนั้นฉันจึงไม่อยากแคสต์เป็น "any"

คำตอบ #1

นี่อาจจะมาช้าไปหน่อย แต่การแปลงคอมโพเนนต์ link เป็น React.ComponentClass เมื่อส่งไปยังคอมโพเนนต์ Button ดูเหมือนจะแก้ปัญหาที่คุณได้อธิบายไว้ได้

วางอันนี้ไว้ตรงนี้เพื่ออ้างอิงในอนาคต

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>