我已經定義了一個組件
type Props = {
label:string,
autoFocus:boolean,
onClick:(e: React.ClickEvent<HTMLInputElement>) => void,
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}
const Input = ({ handleChange, label, autoFocus, handleClick }:Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
}
/>
);
我首先將我的反應組件轉換為打字稿,我有點困惑我應該為我正在檢索它的函式撰寫什么型別的道具,在型別道具初始化之上,我得到那個字串和布林值,但有人應該如何處理事件函式打字
uj5u.com熱心網友回復:
您可以定義handleClick為React.MouseEventHandler<HTMLInputElement>:
import { TextField } from "@material-ui/core";
import React from "react";
type Props = {
label: string;
autoFocus?: boolean;
handleClick?: React.MouseEventHandler<HTMLInputElement>;
handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
/>
);
export default function App() {
return <Input label="CustomInput" />;
}
uj5u.com熱心網友回復:
由于我們希望使用 MUI 來支持型別并成為單一事實來源,因此我建議從 Material UI 本身推斷型別,而不是創建單獨的型別。
import { TextField, TextFieldProps } from '@mui/material';
type Props = {
handleChange: TextFieldProps['onChange'];
handleClick: TextFieldProps['onClick'];
label: TextFieldProps['label'];
autoFocus: TextFieldProps['autoFocus'];
};
const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
/>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368250.html
標籤:javascript 反应 打字稿 材质-ui
上一篇:不能宣告泛型函式可能回傳null
