javascript - Typescript arayüzünde giriş türleri
Yeniden kullanılacak bir bileşen yazmaya çalışıyorum ve değişkenlerden biri render edilmesi gereken giriş türü.
Şu anda benim elimde bu var:
type InputBaseProps = {
children?: ReactChild;
className?: string;
id: string;
label?: string;
name?: string;
onBlur: (event: ChangeEvent<HTMLInputElement>) => void;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
placeholder?: string;
style?: CSSProperties;
type: ????;
value?: string;
};
Sadece geçerli HTML types, örneğin burada tanımlanan tüm listeyi https://www.w3schools.com/tags/att_input_type.asp gibi izin vermek istiyorum
Bunu yapmanın basit bir yolu var mı?
Cevap #1
import { HTMLInputTypeAttribute } from "react";
type InputBaseProps = {
type?: HTMLInputTypeAttribute
}
HTMLInputTypeAttribute şu şekilde çözülür:
type HTMLInputTypeAttribute = "number" | "search" | "button" | "time" | "image" | "text" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "month" | "password" | "radio" | "range" | ... 5 more ... | (string & {})
Intellisense iyi çalışıyor.
Cevap #2
Evet, basit, kullanmak istediğiniz tüm türlerin arasına | koyabilirsiniz. Örneğin, şöyle olur:
"buton" | "onay kutusu" | "renk" | "tarih" | "tarih-saat yerel" | "e-posta" | "dosya" | "gizli" | "resim" | "ay" | "sayı" | "şifre" | "radyo" | "aralık" | "sıfırla" | "arama" | "gönder" | "telefon" | "yazı" | "saat" | "url" | "hafta"
Bunların hepsi soruda listelediğiniz w3schools sayfasından alındı.
Cevap #3
Bunu böyle yapmalısınız:
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
//...add your custom types here
}
