简体   繁体   English

无法读取null反应的属性'appendChild'

[英]Cannot read property 'appendChild' of null react

I am trying to dynamically add new input fields using this js guide . 我正在尝试使用此js指南动态添加新的输入字段。 Everything works with pure js but when I try to adapt it to react I get this error: TypeError: Cannot read property 'appendChild' of null 一切都适用于纯js,但是当我尝试使其适应反应时,出现此错误: TypeError:无法读取null的属性'appendChild'

import React, { Component } from "react";

class addTeams extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
    };
  }


  addInput(divName) {
    var counter = 1;
    var limit = 5;
    if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
  }

  render() {
    return (
      <div class="container">
        <div class="row">
          <div class="col-md-6 col-md-offset-3">
            <div class="jumbotron text-center">
              <form method="POST">
                <div id="dynamicInput">
                  Entry 1<br></br><input type="text" name="myInputs[]"></input>
                </div>
                <input type="button" value="Add another text input" onClick={this.addInput('dynamicInput')}></input>
              </form>
              <button type="submit" onClick={this.addTournament} class="btn btn-primary">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default addTeams;

Did you check that addInput work? 您是否检查过addInput是否正常工作?

In constructor, try to type this.addInput = this.addInput.bind(this); 在构造函数中,尝试键入this.addInput = this.addInput.bind(this);

And you should change the counter variable in addInput scope to state object. 并且您应该将addInput范围中的计数器变量更改为状态对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM