我正在尝试使用this js guide动态添加新输入字段。一切都适用于纯js,但当我尝试调整它以作出反应时我得到这个错误: TypeError:无法读取属性'appendChild'为null
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;
答案 0 :(得分:0)
您是否检查过addInput是否正常工作?
在构造函数中,尝试键入this.addInput = this.addInput.bind(this);
您应该将addInput范围中的计数器变量更改为状态对象。