简体   繁体   English

将 function 作为道具传递给 Typescript 反应功能组件

[英]Passing a function as a prop to a Typescript React Functional Component

I have a functional component (written in Typescript) that needs to pass a handler function down to a child component.我有一个功能组件(用 Typescript 编写)需要将处理程序 function 向下传递给子组件。 Here is a scaled down version of the parent function:这是父 function 的缩小版本:

type Props = { handleLocationChange(): void };

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

In VS Code the search component shows an error:在 VS Code 中,搜索组件显示错误:

Type '{ handleLocationChange: () => void;键入'{ handleLocationChange: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }' 不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }'. }'。 Property 'handleLocationChange' does not exist on type 'IntrinsicAttributes & { children?: ReactNode;类型“IntrinsicAttributes & { children?: ReactNode;”上不存在属性“handleLocationChange” }'.ts(2322) }'.ts(2322)

Any help would be much appreciated.任何帮助将非常感激。 I am sure I am missing something small.我确定我错过了一些小东西。

You need to declare handleLocationChange as a prop on the Search component您需要在 Search 组件上声明 handleLocationChange 作为道具

Code your handler like a function, this way像 function 一样编码你的处理程序,这样

function handleLocationChange(){
    console.log('Location Changed.');
  };

Then it should work然后它应该工作

You need to declare the prop type in Search Component and declare type to parameter too:您需要在搜索组件中声明道具类型并将类型声明为参数:

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

I hope this answer can help who wants to use typescript and want to easy your own life passing functions through components (I don't recomend pass functions through many levels).我希望这个答案可以帮助想要使用 typescript 并希望通过组件轻松传递函数的人(我不建议通过多个级别传递函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM