你好!
我目前正在嘗試制作一個基于提供的物件生成的表單,這似乎適用于我扔給它的任何東西。
也就是說,直到我到達一個嵌套物件。
問題:
一旦我達到 if 條件,(typeof value === "object")我想要一個隱藏的輸入(這有效)。
然后我想進入我剛剛識別的那個物件,進入它可能包含的所有子物件,并按照與初始運行相同的標準生成輸入。
function GenericForm(props: any) {
var object = props.object;
return (
<div>
<form>
{Object.entries(object).map(([property, value]) => {
let type: string = "";
if (typeof value === "string") {
type = "text";
} else if (typeof value === "number") {
type = "number";
} else if (typeof value === "boolean") {
type = "checkbox";
} else if (value instanceof Date) {
type = "date";
} else if (typeof value === "object") {
type = "hidden";
}
return [
<label property={property} htmlFor={property}>
{property}
</label>,
<input
type={type}
id={property}
name={property}
defaultValue={value as string}
onChange={(newVal) => {
object[property] = newVal.target.value;
}}
/>,
];
})}
</form>
</div>
);
}
export default GenericForm;
我知道這很可能使用了某種遞回,雖然我嘗試使用遞回來解決它,但我無法解決它。
此處粘貼的代碼來自我嘗試遞回之前,以便從我出錯的地方獲得“干凈的作業表”。
編輯 1 - 添加關于物件結構的資訊
傳遞的物件應該是完全通用的,并允許將任何結構的物件傳遞給組件,目前它應該只評估屬性的型別并從中創建輸入元素。
我傳遞的當前物件之一具有以下 JSON 架構
{
"id": "XYZ1",
"type": "twilio-api",
"sid": "someSID",
"from": " phonenumberhere",
"name": "TWILIO SMS",
"credentials": {
"token": "someapitoken"
}
}
上面的物件當前呈現如下:

uj5u.com熱心網友回復:
假設你有一個Input組件:
function Input = ({ name, type, value }) => {
// most of your code can fit here
return <input name={name} type={type} value={value} />
}
您可以使用您的代碼版本,我使用了上面的簡化版本,以使我們的討論更容易。有了它,我們可以設計一個InputList組件:
function InputList = ({ object }) => {
console.log('list', object)
return (
<div>
{Object.entries(object).map(([property, value]) => {
if (typeof value === "object") {
return <InputList object={value} />
} else {
return <Input name={property} />
}
})}
</div>
)
}
你可以看到在 this 里面InputList,有一個InputList再次呼叫,這就是你正在尋找的遞回。當物件內不再有物件時,遞回停止。
注意:React需要value并onChange驅動任何input盒子。否則,它們只會表現得像本機輸入。但這不是這個問題的一部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371532.html
標籤:javascript 反应 打字稿 形式 递归
