我是 Typescript 的新手,我必須撰寫一個父組件,該組件將 onClick 作為道具發送到子組件,其中有一個按鈕,單擊時會觸發 onClick 的功能。
這是代碼:
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} />
);
}
對于子組件不知道怎么定義介面,這里應該放什么?
export interface ChildComponentProps {
onClick: <unknown>(); // what to add here?
}
這是子組件:
export function ChildComponent({onClick}: ChildComponentProps) {
...
return (
<div>
...
<ButtonComponent
onClick={() => onClick()}
...
/>
...
);
}
有什么想法可以添加到界面中,或者是否應該進行任何其他更改才能使 Typescript 正確?
uj5u.com熱心網友回復:
對于像 onClick 這樣的函式,你必須描述輸入引數和輸出或者只寫函式(盡管為了更好的型別檢查你不應該只寫函式)。
所以像這樣:
onClick: () => void
例如,如果你的函式得到一個數字并回傳一個字串,你應該這樣寫:
onClick: (n: number) => string
uj5u.com熱心網友回復:
父組件:
interface OnClickIdInterface {
(): void,
}
export interface parentPropsInterface {
onClick?: OnGetIdInterface;
}
render() {
return <ChildComponent onClick={(id) => this.onClick(id)}/>
}
子組件:
const HomePresentation: React.FunctionComponent<parentPropsInterface> = ({onClick}) => {
return (
<div onClick={()=>onClick()}>
some content
</div>
)
}
uj5u.com熱心網友回復:
以下代碼應該可以作業。但這取決于ButtonComponent. 用作React.MouseEventHandler<T = Element>型別。
export interface ChildComponentProps {
onClick: React.MouseEventHandler<ButtonComponent>
}
export function ChildComponent({onClick}: ChildComponentProps) {
...
return (
<div>
...
<ButtonComponent
onClick={() => onClick()}
...
/>
...
);
}
如果這不正確,請通知我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375608.html
標籤:javascript 反应 打字稿 反应钩子
上一篇:知道前兩個點和到下一個點的距離,如何獲得下一個點的坐標
下一篇:無法將值從組件傳遞到模板
