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

javascript - เพิ่มประเภทสำหรับคุณสมบัติ onClick ซึ่งอยู่ใน ...props ใน React TypeScript


ฉันมีคอมโพเนนต์ปุ่มซึ่งฉันพยายามเขียนชนิดของ prop โดยใช้ type และฉันเห็นข้อผิดพลาดนี้ในคอนโซล มีใครช่วยได้ไหม?

Type '{ children: string; label: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & Props'.
  Property 'onClick' does not exist on type 'IntrinsicAttributes & Props'.  TS2322

บทความจากโค้ดของฉัน

type Props = {
  label: string;
  children: ReactNode;
};

const Button = ({ label, children, ...props }: Props) => (
  <button label={label} {...props}>
    {children}
  </button>
);

คำตอบ #1

คุณจำเป็นต้องเพิ่ม onClick เข้าไปใน Props ดังนี้:

type Props = {
  label: string;
  children: ReactNode;
  onClick: () => void;
};