将函数作为 prop 传递给 Typescript React 函数组件

Jos*_*ott 4 javascript typescript reactjs react-props react-functional-component

我有一个功能组件(用 Typescript 编写),需要将处理函数传递给子组件。这是父函数的缩小版本:

type Props = { handleLocationChange(): void };

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

在 VS Code 中,搜索组件显示错误:

类型 '{handleLocationChange: () => void; }' 不可分配给类型 'IntrinsicAttributes & {children?: ReactNode; }'。类型“IntrinsicAttributes & {children?: ReactNode;”上不存在属性“handleLocationChange” }'.ts(2322)

任何帮助将非常感激。我确信我错过了一些小事。

Dan*_*ira 7

您需要在搜索组件中声明 prop 类型,并声明参数类型:

\n
//use this type to both components (children and parent)\ninterface FuncProps {\n    //here you can declare the return type (here is void)\n    handleLocationChange: (values: any) => void;\n}\n//children start\n// here are the tip, define the type in the React.FC and in the FC's parameters itself\nconst Search: React.FC<FuncProps> = (props: FuncProps) => {\n    ... your component behavior and view ...\n    return (\n        {/*\xe2\x86\x93\xe2\x86\x93\xe2\x86\x93\xe2\x86\x93 use the prop like this \xe2\x86\x93\xe2\x86\x93\xe2\x86\x93\xe2\x86\x93*/}\n        <input onClick={props.handleLocationChange('something if you need')}/>\n    )\n};\n//children end\n\n// parent start\nconst Sidebar: React.FC<Props> = (props: FuncProps) => { \nreturn (\n   <>\n      <Search handleLocationChange={props.handleLocationChange} /> \n   </>\n)\n}\n//parent end\n
Run Code Online (Sandbox Code Playgroud)\n

我希望这个答案可以帮助那些想要使用打字稿并希望通过组件传递函数来简化自己的生活的人(我不建议通过多个级别传递函数)。

\n