[英]Generic type in reactjs
我在我的應用程序中為句柄輸入編寫了一個自定義鈎子。 我使用泛型類型來定義我的自定義鈎子返回的類型。 這是我的代碼
interface IUseInput<T, U> {
(): [T, (e: ChangeEvent<HTMLInputElement>) => void, U];
}
function useInput<T, U>(): IUseInput<T, U> {
const [input, setInput] = useState({});
const [isDirty, setDirty] = useState({});
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInput({
...input,
[e.target.name]: e.target.value
});
setDirty({
...isDirty,
[e.target.name]: true
});
};
return [input, handleInputChange, isDirty] //this line get error
}
const Component: React.FC = () => {
const [input, handleChangeInput, isDirty] = useInput<{username: string, password: string}, {username: boolean, password: boolean}>();
return (
....
)
}
但我收到此錯誤Type '{}[]' is not assignable to type 'IUseInput<T, U>
我的錯在哪里? 請幫我
IUseInput<T, U>
是函數的類型,而不是返回類型的類型。 無法指定函數聲明的類型,只能指定變量的類型(您可以為其分配函數)。 然而,這並不是真正必要的,我只是將返回類型從IUseInput
移動到函數聲明中。
可以進行改進,因為U
應該具有與T
相同的鍵,您可以使用預定義的映射類型Record
從T
派生U
。 所以你可以用Record<keyof T, boolean>
替換U
:
function useInput<T>(): [T, (e: ChangeEvent<HTMLInputElement>) => void, Record<keyof T, boolean>] {
const [input, setInput] = useState({} as T);
const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInput({
...input,
[e.target.name]: e.target.value
});
setDirty({
...isDirty,
[e.target.name]: true
});
};
return [input, handleInputChange, isDirty]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.