如何以可赋值类型将函数从父组件传递给子组件



我是TypeScript的新手,我想把我的函数onDogSelected传递给子组件<Dogs />

当我尝试的时候,我得到了一些错误信息,像这样:

Type '{ onDogSelected: (e: any) => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.Property 'onDogSelected' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
我不知道这是什么意思。我一直在想办法,但还是没有解决办法。
const HomePage: React.FC = () => {
const [dogSelected, setDogSelected] = useState("");
const onDogSelected = (e: any) => {
setDogSelected(e.target.value)
}
return (
<ApolloProvider client={client2}>
<Dogs onDogSelected={onDogSelected} />
{dogSelected && <span>{dogSelected}</span>}
</ApolloProvider>
);
};
export default HomePage;

不推荐使用React.FC,应该使用React.FunctionComponent

React.FunctionComponent是泛型类型。你应该把组件的props传递给它。

所以Dogs组件应该看起来像,

import { FunctionComponent } from "react";
const Dogs: FunctionComponent<DogsProps> = (props) => {
...
};
interface DogsProps {
onDogSelected(e: any): void;
}

不必创建接口或类型,只需将其作为参数传递

const Dogs: FunctionComponent<{ onDogSelected(e: any): void; }> = (props) => {

相关内容

  • 没有找到相关文章

最新更新