是否可以有动态类型?我有一个这样的 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 钩子(Hook)变量的类型。 有可能吗?
repo 链接: https://github.com/johnathan-codes/react-form-from-json
最佳答案
其他响应也可以,但它们没有充分利用 typescript 的全部功能。您想要的是在字段 inputType
和 type
之间建立关系,这样带有 {inputType: "checkbox"}
的字段必须始终是 boolean
,{inputType: "text"}
必须始终是 string
,等等。
以下是使用 a Union Type 执行此操作的方法(您也可以使用映射或条件,但我不会涉及)。
type FieldPropInterface = {
fieldName: string;
} & ({
type: "string";
inputType: "text";
} | {
type: "boolean";
inputType: "checkbox";
})
你需要多读一点the HTML input element及其 Prop ,因为您想以不同于文本输入的方式对待复选框。复选框通过名为 checked
的 boolean
属性设置它们的值,而不是 value
,它是一个字符串。 npm 上还有大量的包可以使处理表单变得更加容易。
如果您希望useState
是通用的,那么您的组件Field
应该是通用的。
您还说过您的 FieldInterface.handler
可以是任何类型的 Function
,但您需要具体说明该函数是什么。
{ handler: (e: ChangeEvent<HTMLInputElement>) => void; }
或者它可以成为 value
的函数,而不是具有不同设置的 event
。
当使用大写名称 String
时,您确定知道自己在做什么吗?大写的名称表示该值是 String 构造函数,而小写的名称表示该值是 string
。来自 the docs :
Don't ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
如果您使用它作为标志,只是说“这个值是一个字符串”或“这个值是一个 bool 值”,您可以考虑使用文字字符串 "string"
和 “boolean”
而不是对象构造函数,但我不知道它在您的代码中实际使用的位置和方式。
关于javascript - React Typescript - 动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64208371/