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

reactjs - ประเภท TypeScript ที่ถูกต้องสำหรับ children ของ React คืออะไร?


ฉันกำลังพยายามกำหนดชนิดของ props สำหรับคอมโพเนนต์ที่แมป children อย่างถูกต้อง:

type Props = {
    children: any
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

ฉันได้ใช้ JSX.Element แต่รู้สึกว่านั่นมันไม่ค่อยถูกต้องนัก

คำตอบ #1

เมื่อตรวจสอบโค้ดภายใต้ DefinitelyTyped ดูเหมือนว่า children จะถูกกำหนดชนิดเป็น ReactNode

ตัวอย่าง :

type Props = {
    children: ReactNode
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

หมายเหตุ: ประเภท ReactNode สามารถพบได้ในเนมสเปซของ React:

import React from 'react';

let someNode: React.ReactNode;

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