如何在React中迭代json-schema结构?

时间:2019-01-09 09:44:59

标签: json reactjs forms

我是新来的反应者。我做了一个json结构,以进行反应以构建组件。我不关心布局,因为我假设是垂直布局。 对于要开发的简单表单,可以从json文件中呈现8个组件,如下所示:

  1. 名称输入框
  2. 用户名输入框
  3. 电子邮件输入框
  4. 密码输入框
  5. 国家/地区下拉列表
  6. 性别单选按钮

  7. 语言复选框

  8. 提交按钮

json文件如下:

apply plugin: com.myown.plugin.AwesomePlugin

现在我的问题是我应该如何遍历此json文件并获取react中的每个组件?我该如何应对?

2 个答案:

答案 0 :(得分:0)

对我来说,似乎只是一个对象数组。

可以使用以下方法完成数组的迭代:

myjson.forEach(singleObject => {
  // my things here
})

或者,如果需要将这些对象映射到组件以呈现它们:

myjson.map(singleObject => {
  // return a rendered component here
})

我假设您已经具有渲染和向下传递道具的组件...

答案 1 :(得分:0)

附加到 0xc14m1z 答案时,您需要使用地图来遍历属性并呈现表单:

class A extends React.Component {
    render() {
        const a = {
            "items": [
                {
                    "componentType": "NameBox",
                    "lable": "name",
                    "properties": {
                        "type": "string",
                        "minLength": 3,
                        "description": "Enter Your Name"
                    }
                },
                {
                    "componenetType": "UserNameBox",
                    "lable": "username",
                    "properties": {
                        "type": "string",
                        "minLength": 4,
                        "maxLength": 8,
                        "description": "Enter user name"
                    }
                },
            ]
        }

        return <div>
            {a.items.map(value => {
                return <div>
                    <h3>{value.lable}</h3><input type={value.properties.type} minLength={value.properties.minLength} maxLength={value.properties.maxLength} placeholder={value.properties.desicription} />
                </div>
            })}
        </div>
    }
}

ReactDOM.render(<A />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

相关问题