[英]Send onClick function as props to a component in React with Typescript
I'm new to Typescript and I have to write a parent component that sends as props onClick to the child component where is a button that triggers the functionality of onClick when clicked.我是 Typescript 的新手,我必须编写一个父组件,将 onClick 作为道具发送到子组件,其中是一个按钮,当点击时触发 onClick 的功能。
Here is the code:这是代码:
export function ParentComponent(props: ParentComponentProps) {
const [isOpened, toggleModal] = useToggle(false);
// useToggle is a custom hook that toggles a boolean
...
const onClick = () => {
toggleModal();
}
return (
<ChildComponent onClick={onClick} />
);
}
For the child component I don't know how to define the interface, what should be put here?对于子组件我不知道怎么定义接口,这里应该放什么?
export interface ChildComponentProps {
onClick: <unknown>(); // what to add here?
}
And here is the child component:这是子组件:
export function ChildComponent({onClick}: ChildComponentProps) {
...
return (
<div>
...
<ButtonComponent
onClick={() => onClick()}
...
/>
...
);
}
Any ideas what to add to the interface or if there should be any other changes to be Typescript correct?有什么想法要添加到界面中,或者是否应该进行任何其他更改以使 Typescript 正确?
For functions like onClick, you have to describe input arugments and output or just write Function (although for better type checking you shouldn't just write Function).对于像 onClick 这样的函数,你必须描述输入参数和 output 或者只写 Function(尽管为了更好的类型检查你不应该只写函数)。
So something like this:所以是这样的:
onClick: () => void
If for example your function gets a number and returns a string, you should write it like this:例如,如果你的 function 得到一个数字并返回一个字符串,你应该这样写:
onClick: (n: number) => string
Parent Component:父组件:
interface OnClickIdInterface {
(): void,
}
export interface parentPropsInterface {
onClick?: OnGetIdInterface;
}
render() {
return <ChildComponent onClick={(id) => this.onClick(id)}/>
}
Child Component:子组件:
const HomePresentation: React.FunctionComponent<parentPropsInterface> = ({onClick}) => {
return (
<div onClick={()=>onClick()}>
some content
</div>
)
}
Following code should work.以下代码应该可以工作。 But it depends on
ButtonComponent
.但这取决于
ButtonComponent
。 Used React.MouseEventHandler<T = Element>
as type.使用
React.MouseEventHandler<T = Element>
作为类型。
export interface ChildComponentProps {
onClick: React.MouseEventHandler<ButtonComponent>
}
export function ChildComponent({onClick}: ChildComponentProps) {
...
return (
<div>
...
<ButtonComponent
onClick={() => onClick()}
...
/>
...
);
}
Please notify me if this is incorrect.如果这不正确,请通知我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.