[英]React Typescript - dynamic types
是否可以有動態類型? 我有一個這樣的json
{
"fieldName": "Some text",
"type": String,
"inputType": "text"
},
{
"fieldName": "Some bool",
"type": Boolean,
"inputType": "checkbox
}
並且基於那個 json 我想呈現這樣的字段組件
const Field: React.FC<FieldInterface> = ({ name, type, handler }) => {
const [value, setValue] = useState<type>()
const handleOnChane = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
handler(name, e.target.value)
}
return (
<div>
<label htmlFor={name}>{name}</label>
<input
type={type}
id={name}
onChange={handleOnChane}
value={value}
></input>
</div>
)
}
export default Field
這是我的界面
export interface FormInterface {
fields: FieldPropInterface[]
submitAction: Function
}
export interface FieldPropInterface {
name: string
inputType: string
type: <Here I would like to have something but don't know what>
}
export interface FieldInterface {
name: string
type: string
handler: Function
}
你看,我需要那個類型來設置 useState 鈎子變量的類型。 有可能這樣做嗎?
回購鏈接: https : //github.com/johnathan-codes/react-form-from-json
使用替代類型。
export interface FieldPropInterface {
name: string;
inputType: string;
type: Boolean | String;
}
其他響應將起作用,但它們沒有利用打字稿的全部功能。 您想要的是在inputType
和type
字段之間建立關系,使得{inputType: "checkbox"}
字段必須始終為boolean
, {inputType: "text"}
必須始終為string
,依此類推。
下面是如何使用聯合類型來做到這一點(你也可以使用地圖或條件,但我不會進入)。
type FieldPropInterface = {
fieldName: string;
} & ({
type: "string";
inputType: "text";
} | {
type: "boolean";
inputType: "checkbox";
})
您需要更多地閱讀HTML 輸入元素及其道具,因為您希望將復選框與文本輸入區別對待。 復選框通過一個叫做checked
的boolean
屬性來設置它們的值,而不是一個字符串value
。 npm 上還有很多包可以讓處理表單變得更加容易。
如果您希望useState
是通用的,那么您的組件Field
應該是通用的。
您還說過您的FieldInterface.handler
可以是任何類型的Function
,但您需要具體說明該函數是什么。
{ handler: (e: ChangeEvent<HTMLInputElement>) => void; }
或者它可以成為value
的函數而不是具有不同設置的event
。
在使用大寫名稱String
時,您確定知道自己在做什么嗎? 大寫名稱表示該值是 String 構造函數,而小寫表示該值是一個string
。 從文檔:
永遠不要使用類型 Number、String、Boolean、Symbol 或 Object 這些類型是指幾乎從未在 JavaScript 代碼中正確使用的非原始盒裝對象。
如果您使用它作為標志,只是說“這個值是一個字符串”或“這個值是一個布爾值”,您可能會考慮使用文字字符串"string"
和"boolean"
而不是對象構造函數,但我不不知道在您的代碼中實際使用的位置和方式。
你也可以做這樣的事情:
export interface FieldInterface<T> {
name: string
type: T
handler: Function
}
const Field: React.FC<FieldInterface<typeof type>> = ({ name, type, handler }) => {
const [value, setValue] = useState<type>()
const handleOnChane = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
handler(name, e.target.value)
}
return (
<div>
<label htmlFor={name}>{name}</label>
<input
type={type}
id={name}
onChange={handleOnChane}
value={value}
></input>
</div>
)
}
export default Field
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.