是否可以有动态类型?我有一个这样的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