【问题标题】:Uncaught Invariant Violation: Objects are not valid as a React child for HTML Form未捕获的不变违规:对象作为 HTML 表单的 React 子项无效
【发布时间】:2016-08-24 16:53:51
【问题描述】:

我编写了一个函数来基于对象的键和值构建 HTML 表单,我试图在我的 render 方法中返回该表单。但是,我不断收到错误消息:

ReactJs 0.14 - Invariant Violation: Objects are not valid as a React child

这是我的createForm() 方法:

  createForm() {

    const obj = {

    }

    const object_fields = resourceFields.fields;
    let form = document.createElement('form');

    _.forIn(object_fields, function(field_value, field_name) {


        let div = document.createElement('div');
        div.setAttribute('className', 'form-control');

        let label = document.createElement('label');
        label.setAttribute('htmlFor', 'name');
        label.innerHTML = field_name;

        let input = document.createElement('input');
        input.setAttribute('className', 'form-control');
        input.setAttribute('type', 'text');
        input.setAttribute('ref', field_name);
        input.setAttribute('id', field_name);
        input.setAttribute('value', field_value);
        input.setAttribute('onChange', '{this.handleChange}');

        div.appendChild(label);
        div.appendChild(input);
        form.appendChild(div);

    })

    console.log(form) //this prints out fine

    return form


  }

这是我的render() 方法:

render() {
  return (
      <div>
        {this.createForm()}
      </div>
    )
}

有人知道会发生什么吗?我的表单在控制台中打印出来就好了...提前致谢!

【问题讨论】:

    标签: object reactjs


    【解决方案1】:

    在使用 React 时,您永远不会操作实际的 DOM 节点。当您在 render 函数中构建 UI 时,JSX 标记被转换为纯 JavaScript(React.createElement 函数调用),从而构建 DOM 的表示

    因此,在您的情况下,您应该返回 createForm 中的 JSX,而不是 DOM 元素。

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 2019-09-09
      • 2018-06-13
      • 2018-12-16
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      相关资源
      最近更新 更多