Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用JSON响应表单问题_Reactjs - Fatal编程技术网

Reactjs 使用JSON响应表单问题

Reactjs 使用JSON响应表单问题,reactjs,Reactjs,我有一个表单,其字段格式如下 <Form.Field> <input type="text" name="firstname" placeholder="First Name" value= { this.

我有一个表单,其字段格式如下

                  <Form.Field>
                    <input 
                        type="text" 
                        name="firstname" 
                        placeholder="First Name" 
                        value= { this.state.user.firstname } 
                        onChange= { this.onChange } 
                    />
                  </Form.Field>
最初,我试图让JSON对象从API返回,并在名称周围嵌套层次结构

 state = {
    user: { 
     name: {
      firstname: "",
      lastname: ""
     }
   }
 }
但在这种情况下,我的onChange对象将变量添加到我的状态,而不是管理现有的变量;即使触发事件,我也不会更改UI上的值。我试图通过操纵form.field的名称来匹配JSON来导航JSON层次结构,但没有成功:

                  <Form.Field>
                <input 
                    type="text" 
                    name="name.firstname" 
                    placeholder="First Name" 
                    value= { this.state.user.name.firstname } 
                    onChange= { this.onChange } 
                />
              </Form.Field>


我遗漏了什么?

您的假设很好,无法使用以下语法在react中导航JSON对象:
{[e.target.name]:e.target.value}

最简单的解决方案是使用不同的
onChange
函数,专门修改
名称
子对象

如果您仍然希望使用单个函数,那么应该可以解析
e.target.name
值并拆分
字符上的字符串,但我觉得这听起来很奇怪

                  <Form.Field>
                <input 
                    type="text" 
                    name="name.firstname" 
                    placeholder="First Name" 
                    value= { this.state.user.name.firstname } 
                    onChange= { this.onChange } 
                />
              </Form.Field>