javascript - Bir fonksiyonu prop olarak Typescript React Fonksiyonel Bileşenine geçirmek


Fonksiyonel bir bileşenim var (Typescript ile yazılmış) ve bir işleyici fonksiyonu alt bileşene iletmesi gerekiyor. İşte üst bileşen fonksiyonunun küçük bir versiyonu:

type Props = { handleLocationChange(): void };

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

VS Code'da arama bileşeni bir hata gösteriyor:

'{ handleLocationChange:() => void; }' türü 'IntrinsicAttributes & { children?: ReactNode; }' türüne atanamaz. Property 'handleLocationChange' 'IntrinsicAttributes & { children?: ReactNode; }' türünde mevcut değil.ts(2322)

Her türlü yardım çok takdir edilecektir. Eminim küçük bir şeyi kaçırıyorum.

Cevap #1

Search Bileşeninde prop tipini belirtmeniz ve parametreye de tipi belirtmeniz gerekiyor:

//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

Umarım bu cevap, TypeScript kullanmak isteyen ve fonksiyonları bileşenler arasında geçirmek suretiyle kendi hayatlarını kolaylaştırmak isteyenlere yardımcı olur (fonksiyonları birçok seviye boyunca geçirmeyi önermem).

Cevap #2

handleLocationChange'i Search bileşeninde bir prop olarak tanımlamanız gerekiyor

İlgili makaleler