Bootstrap

推荐一种编辑任意复杂JOSN数据的简单易方法

  • 如果你有需求让用户编辑JSON数据,你会怎么做?
  • 如果JSON对象的结构非常复杂你又会怎么做?

比如下面的JSON对象:

  {
      "name": "John Doe",
      "age": 30,
      "isEmployed": true,
      "skills": ["JavaScript", "Python", "HTML"],
      "vip":true,
      "level":1,
      "address": {
          "street": "TongYan",
          "city": "QuanZhou"
      },
      books:[
          { name:"AutoStore",price:100,count:12 },
          { name:"AutoStore for React",price:200,count:1 }
      ]
  }

实际JSON可能会更复杂,推荐一种很简单的方式,使用AutoStore,如下:

import { useForm } from "@autostorejs/react"
export default ()=>{
  const { Form,reset } = useForm({
      "name": "John Doe",
      "age": 30, 
      "skills": ["JavaScript", "Python", "HTML"],
      "vip":true,
      "level":1,
      "address": {
          "street": "TongYan",
          "city": "QuanZhou"
      },
      books:[
          { name:"AutoStore",price:100,count:12 },
          { name:"AutoStore for React",price:200,count:1 }
      ]
  })
  return (
     <Form>
       <input data-field-name="name"/>
       <input data-field-name="skills"/>
       <input data-field-name="age" type="number/>
       <input data-field-name="level" type="number/>
       <input data-field-name="vip" type="checkbox/>
       <input data-field-name="address.city" type="checkbox"/>
       <input data-field-name="address.street" type="checkbox"/>
       {
           books.map((book,index)=>{
               return (<>
                  <input data-field-name={`books.${index}.name`} />
                  <input data-field-name={`books.${index}.price`} />
                  <input data-field-name={`books.${index}.count`} />
              </>)
           })
       }
     </Form>  
  )
}

好了,就这么简单,只需要为input/textarea/select等表单控件指定一个data-field-name属性指向要绑定的数据在JSON对象中的路径,就可以轻构建立起表单与JSON对象之间的双向绑定关系,数据会自动同步到JSON中。

AutoStore是一款非常优秀的前端React状态库,可以轻松实现任意复杂JSON数据对象与表单控件之间的双向绑定。

;