javascript - Videregive en funktion som en prop til en Typescript React funktionel komponent
Jeg har en funktionel komponent (skrevet i Typescript), der har brug for at sende en håndteringsfunktion ned til en børnekomponent. Her er en nedskaleret version af forældre-funktionen:
type Props = { handleLocationChange(): void };
const Sidebar: React.FC<Props> = (props) => {
const handleLocationChange = () => {
console.log('Location Changed.');
};
return (
<>
<Search handleLocationChange={handleLocationChange} />
</>
)
}
I VS Code viser søgekomponenten en fejl:
Type ''{ handleLocationChange:() => void; }'' kan ikke tildeles typen ''IntrinsicAttributes & { children?: ReactNode; }''. Egenskaben ''handleLocationChange'' findes ikke på typen ''IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)
Enhver hjælp ville blive meget værdsat. Jeg er sikker på, at jeg mangler noget småt.
Svar #1
Du skal erklære prop-typen i Search-komponenten og erklære typen for parameteren også:
//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
Jeg håber, dette svar kan hjælpe dem, der ønsker at bruge TypeScript og ønsker at gøre deres eget liv lettere ved at sende funktioner gennem komponenter (jeg anbefaler ikke at sende funktioner gennem mange niveauer).
Svar #2
Du skal erklære handleLocationChange som en prop på Search-komponenten
