如何将函数从父组件传递给类型为 assingable 的子组件

How to pass function from parent component to child component with type assingable

我是 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) => {