我正在创建一个示例动态表单,并希望基于JSON加载我的输入元素,该JSON包含不同的输入元素,如"TextBox"、"Text-Area"、"DropDown"、"Radio-Input"等. I have a JSON file created to get this as shown below:个
[
{
"id": "1",
"type": "textbox",
"text": "",
"required": true,
"label": "lbl"
},
{
"id": "2",
"type": "textbox",
"text": "",
"required": true,
"label": "Specification Name"
},
{
"id": "3",
"type": "dropdown",
"text": "",
"required": true,
"label": "Specification Reviewed",
"options":["a","2"]
},
{
"id": "4",
"type": "dropdown",
"text": "",
"required": true,
"label": "Action Required",
"options":["1","2","3"]
},
{
"id": "5",
"type": "textbox",
"text": "",
"required": true,
"label": "lbl"
}
]
我有一个基于App的组件,它调用另一个名为"Input"的组件,该组件具有我的布局,我通过该组件检索元素.我可以在这里拉出文本框和下拉列表,但我不能遍历下拉列表 Select .我不知道该怎么做.
Here's my App Base solution:在这里,我使用map概念从JSON本地文件获取数据,并将其分配给inputvalues,然后在return中的form标记中使用它.
- 我能够动态列出我的所有输入元素
- But I'm not able to get the dropdown values from my JSON file个
function App() {
const [inputObject, setInputObject] = React.useState(inputData)
const inputvalues = inputObject.map( input => {
return (
<Input
key={input.id}
input={input}
/>
)
})
const handleSubmit = (event) => {
event.preventDefault();
}
return (
<div className="App">
<header className="App-header">
<form>
<div>
{inputvalues}
</div>
<input type="submit" value="submit" onClick={handleSubmit} />
</form>
</header>
</div>
);
}
export default App;
And, here's my input.js component file:这基本上是布局输入元素,我使用props 获取数据,但我无法获取下拉列表 Select 值,因为我需要以某种方式在每个下拉列表元素中迭代.
export default function Input(props) {
const [state, setState] = React.useState({
textBoxValue: ""
})
function handleChange(evt) {
setState({ [props.input.id] : evt.target.value });
}
if (props.onChange) {
props.onChange(state);
}
return (
<div>
<label>{props.input.type}: </label>
{props.input.type === "textbox" && <input name={props.input.type} placeholder={props.input.type} id={props.input.id} value={state.firstName} onChange={handleChange}/>}
{props.input.type === "dropdown" && <select name={props.input.type} id={props.input.id}>
<option value={props.input.options}></option></select>
}</div>)}
请帮助我或 bootstrap 我,因为我还在学习react . 除此之外,我以后如何在表单提交时获得所有输入值?为此,我try 添加一个handleChange事件,以查看数据是否通过,但不起作用.
提前谢谢你了!