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

reactjs - ไม่พบคุณสมบัติในประเภท 'IntrinsicAttributes & { children?: ReactNode; }'


ฉันมีโปรเจกต์ React ที่สร้างด้วย Create-React-App ซึ่งมีแพ็กเกจดังต่อไปนี้ (ระบุแพ็กเกจที่เกี่ยวข้องกับปัญหาของฉัน):

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
"typescript": "^3.9.2",
"@typescript-eslint/eslint-plugin": "^2.33.0",
"@typescript-eslint/parser": "^2.33.0"

ฉันได้สร้าง HOC แบบง่าย ๆ ขึ้นมา (ซึ่งตอนนี้ยังไม่ทำอะไร แต่ฉันจะเพิ่มตรรกะของฉันในภายหลัง) แบบนี้:

type Props = {
    [key: string]: any;
};


const connect = function (Component: FunctionComponent): FunctionComponent {
    const ComponentWrapper = function (props: Props): ReactElement {
        return <Component {...props} />;
    };

    return ComponentWrapper;
};

และฉันได้ส่งออกคอมโพเนนต์ของฉันแบบนี้ :

    const Test: FunctionComponent<Props> = function ({ message }: Props) {
        return (
            <div>{message}</div>
        );
    };


export default connect(Test);

และการใช้ส่วนประกอบนี้แบบนี้ :

<Test message="Testing message" />

แต่ได้รับข้อผิดพลาดในคอมไพเลอร์ :

Type '{ message: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'message' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.  TS2322

ฉันได้ลองสิ่งที่ผู้คนแนะนำในคำถาม Stack Overflow ที่คล้ายกันอื่น ๆ และบทความที่พบใน Google แล้ว แต่จนถึงตอนนี้ก็ยังไม่มีอะไรได้ผล

คำตอบ #1

// This is the piece we were missing --------------------v
const connect = function (Component: React.FC): React.FC<Props> {
    const ComponentWrapper = function (props: Props): JSX.Element {
        return <Component {...props} />;
    };

    return ComponentWrapper;
};

และหลังจากรีสตาร์ทคอมไพเลอร์ มันก็จะทำงานได้ดี

ชนิดของค่าที่ส่งกลับของฟังก์ชัน connect คือคอมโพเนนต์เชิงฟังก์ชันที่ต้องการ Props ไม่ใช่คอมโพเนนต์เชิงฟังก์ชันเปล่า

ดูแผ่นสรุปด้วย

บทความที่เกี่ยวข้อง