所以這個問題在過去的幾天里一直困擾著我,我發誓我已經看過幾乎所有試圖解決它的人。我只需要在子組件內部呼叫從父組件 onClick傳遞的函式。該函式接受引數,引數部分是錯誤所在。
我知道我可能可以匯出和匯入該函式,但這是我可以在常規 JavaScript 中輕松完成并做出反應的事情,所以我確信它一定是可行的。我只是目前不是最能勝任 TypeScript 的人。
父組件
// Promise Function I am passing to the child
function parentFunction(email: string, password: string, userName: string) {
return promiseFunction(email, password)
.then((result) => {
return updateProfile({
displayName: userName,
})
})
.catch((error) => {
console.log(error);
});
}
// Passing to child component
return (
<div>
<ChildComponent parentFunction = {parentFunction}/>
</div>
)
子組件
所以因為它是一個 onClick 函式,我知道我需要處理這個event函式。
type Props = {
parentFunction: (event: React.MouseEvent<HTMLButtonElement>) => Promise<void>;
}
export default function childComponent(props: Props){
return(
<button onClick={props.parentFunction}></button>
)
}
型別問題
現在,如果沒有引數就沒有問題,并且該功能將在單擊時正常作業。然而。
函式是型別
parentFunction(email: string, password: string, userName: string): Promise<void>
onClick 函式的型別
MouseEventHandler<HTMLButtonElement>
我嘗試在Props型別函式中添加引數,但這僅滿足函式型別問題,onClick型別問題仍然存在,反之亦然。
我試圖解決這個問題
type Props = {
parentFunction: (
email: string,
password: string,
userName: string
event?: React.MouseEvent<HTMLButtonElement>
) => Promise<void>;
}
我要解決這個問題了嗎?我是否完全錯過了在打字稿中傳遞函式的重要內容?任何幫助將不勝感激。
uj5u.com熱心網友回復:
你可以這樣嘗試
為子組件添加事件處理程式
export default function childComponent(props: Props){
return(
<button onClick={(e) => props.parentFunction(e)}></button>
)
}
處理程式型別可能如下所示
type Props = {
parentFunction: (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => Promise<void>;
}
實際事件處理程式
const parentFunction = (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482162.html
