首页 > 解决方案 > 如何将函数从父组件传递给具有可分配类型的子组件

问题描述

我是 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;

标签: reactjstypescripttypeerrorreact-component

解决方案


React.FC已弃用,您应该使用React.FunctionComponent.

React.FunctionComponent是泛型类型。如果您不再期待,您应该将组件的道具传递给它。

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

import { FunctionComponent } from "react";

const Dogs: FunctionComponent<DogsProps> = (props) => {
  ...
};

interface DogsProps {
  onDogSelected(e: any): void;
}

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

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

推荐阅读