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

javascript - การส่งฟังก์ชันเป็น prop ไปยัง Typescript React Functional Component


ฉันมีคอมโพเนนต์แบบฟังก์ชัน (เขียนด้วย Typescript) ที่จำเป็นต้องส่งฟังก์ชันตัวจัดการลงไปยังคอมโพเนนต์ลูก นี่คือเวอร์ชันที่ย่อของฟังก์ชันพาเรนท์:

type Props = { handleLocationChange(): void };

const Sidebar: React.FC<Props> = (props) => { 
 const handleLocationChange = () => {
    console.log('Location Changed.');
  };
return (
   <>
      <Search handleLocationChange={handleLocationChange} /> 
   </>
)
}

ใน VS Code ส่วนการค้นหาแสดงข้อผิดพลาด:

ประเภท ' { handleLocationChange:() => void; } ' ไม่สามารถกำหนดค่าให้กับประเภท 'IntrinsicAttributes & { children?: ReactNode; }' ได้ คุณสมบัติ 'handleLocationChange' ไม่มีอยู่ในประเภท 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)

ความช่วยเหลือใด ๆ จะได้รับความชื่นชมอย่างมาก ฉันแน่ใจว่าฉันพลาดบางสิ่งเล็ก ๆ

คำตอบ #1

คุณจำเป็นต้องประกาศประเภทของ prop ในคอมโพเนนต์ Search และประกาศประเภทให้กับพารามิเตอร์ด้วย:

//use this type to both components (children and parent)
interface FuncProps {
    //here you can declare the return type (here is void)
    handleLocationChange: (values: any) => void;
}
//children start
// here are the tip, define the type in the React.FC and in the FC's parameters itself
const Search: React.FC<FuncProps> = (props: FuncProps) => {
    ... your component behavior and view ...
    return (
        {/*↓↓↓↓ use the prop like this ↓↓↓↓*/}
        <input onClick={props.handleLocationChange('something if you need')}/>
    )
};
//children end

// parent start
const Sidebar: React.FC<Props> = (props: FuncProps) => { 
return (
   <>
      <Search handleLocationChange={props.handleLocationChange} /> 
   </>
)
}
//parent end

ฉันหวังว่าคำตอบนี้จะช่วยคนที่ต้องการใช้ TypeScript และต้องการทำให้ชีวิตตัวเองง่ายขึ้นในการส่งฟังก์ชันผ่านคอมโพเนนต์ (ฉันไม่แนะนำให้ส่งฟังก์ชันผ่านหลายระดับ)

คำตอบ #2

คุณต้องประกาศ handleLocationChange เป็น prop บนคอมโพเนนต์ Search

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