我正在创建一个示例动态表单,并希望基于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标记中使用它.

  1. 我能够动态列出我的所有输入元素
  2. 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事件,以查看数据是否通过,但不起作用.

提前谢谢你了!

推荐答案

You may find Yup and Formik useful.
With Yup, you can include types to fields as well as things such as if the field is required.
The example linked should get you in the right direction.

编辑-(在操作 comments 之后)

因此,在不使用任何外部库的情况下,您可以执行以下操作:

// Get a hook function
const {useState} = React;

const INPUTS = [ 
  {
      "id": "1",
      "type": "textbox",
      "value": "",
      "required": true,
      "label": "lbl"
  },
  {
      "id": "2",
      "type": "textbox",
      "value": "",
      "required": true,
      "label": "Specification Name"
  },
  {
      "id": "3",
      "type": "dropdown",
      "value": "",
      "required": true,
      "label": "Specification Reviewed",
      "options":["a","2"]
  },
  {
      "id": "4",
      "type": "dropdown",
      "value": "",
      "required": true,
      "label": "Action Required",
      "options":["1","2","3"]
  },
  {
      "id": "5",
      "type": "textbox",
      "value": "",
      "required": true,
      "label": "lbl"
  }
];

const convertArrayToObject = (array, key, targetKey) => {
  const initialValue = {};
  return array.reduce((obj, item) => {
    return {
      ...obj,
      [item[key]]: item[targetKey],
    };
  }, initialValue);
};

const Form = () => {
  const [formState, setFormState] = useState(
    convertArrayToObject(INPUTS, "id", "value")
  );
  const handleChanges = (keyName) => (e) => {
    const newValue = e.target.value
    setFormState(prev => ({
      ...prev,
      [keyName]: newValue
    }));
  }
  
  console.log(formState);
  
  return (
    <form>
      {INPUTS.map((input, inputIndex) => (
        <div key={inputIndex}>
          <label htmlFor={input.id}>{input.label}</label>
          {input.type === "dropdown" && input.options ? (
              <select onChange={handleChanges(input.id)}>
                {input.options.map((option, optionIndex) => (
                  <option
                    key={optionIndex}
                    value={option}>{option}
                  </option>
                ))}
              </select>
            ) : (
            <input
              id={input.id}
              name={input.id}
              required={input.required}
              type={input.type}
              onChange={handleChanges(input.id)}
              value={formState.value}
              />
          )}
        </div>
      ))}
    </form>
  );
}


ReactDOM.createRoot(
  document.getElementById("root")
).render(
  <Form />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

在编写的一些代码背后有一个小小的推理:

  • Reaction希望在对象上映射时传递一个keyprops (因此我 for each 包装器divoption元素添加了它.
  • 我已经在INPUTS对象上进行了映射以构建初始状态,然后创建了一个onChange处理程序,该处理程序是Curry的,这样它就足够通用,可以在任何地方使用
  • 我只是在更新表单时演示一下formState的变化.

超越

如果您计划将数据提交到API,那么您当然需要某种类型的提交按钮.

<button type="submit">Submit</button

但我会把它作为练习留给你.

希望这个能帮上忙!

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

盒子图显示不正确

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

如何在 JSonPath 中按值查找列表中的所有元素

Oracle json 对象的最后一个值不在引号中

JOLT JSON 将值从一对多转换为一对一

如何将 XML 转换为 PsCustomObject 以允许最终导出为 JSON?

从 json 对象中过滤掉所有出现的给定属性

如何使用 Swiftui 判断 JSON 是否缺少键值对

如何从 rails 中的 respond_to 方法生成 json?

JSON.NET 中特定对象的自定义转换

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

反序列化大型 json 对象的 JsonMaxLength 异常

Jackson 中的 readValue 和 readTree:何时使用哪个?

从 JSON 创建 Hashtable

使用 application/json 优于 text/plain 的优势?

JSON 和 BSON 哪个更轻量级?

如何在 JAVA 中对 JSONArray 进行排序

JSON键是否需要唯一?