外部产生的Div

时间:2018-09-09 18:29:17

标签: reactjs

我想用下面的代码创建一个div。但是div是在根div之外创建的。

addDiv = (e) => {
    e.preventDefault();
    //https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
    //create a new div element
    const newDiv = document.createElement("div");
    //and give it some content
    const newContent = document.createTextNode("Hi there");
    //add the text node to the newly created div
    newDiv.appendChild(newContent);
    //add the newly created element and its content into the DOM
    const currentDiv = document.getElementById("div1");
    document.body.insertBefore(newDiv, currentDiv);   
} 





        <div className="App">
            <h1>Generate Divs</h1>
            <div onClick={this.addDiv} id="div1">
                hi
            </div>
        </div>

1 个答案:

答案 0 :(得分:2)

针对此问题,请使用React状态或变量。

class App extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = {
      myDivs: []
    }
  }
  
  addDiv = (e) => {
    e.preventDefault();
    let newDiv = <div>Hi there</div>
    this.setState({myDivs: [...this.state.myDivs, newDiv]})
  }
  
  render() {
    return (
      <div className="App">
        <button onClick={this.addDiv}>Add Item</button>
        <div id="div1"><h1>Hello</h1></div>
        {this.state.myDivs}
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

如果您坚持使用React不推荐的这种DOM操作,那么我建议使用document.body.insertBefore这样的事情会给我一个错误:

addDiv = (e) => {
  e.preventDefault();
  const newDiv = document.createElement("div");
  const newContent = document.createTextNode("Hi there");
  newDiv.appendChild(newContent);
  const currentDiv = document.getElementById("div1");
  currentDiv.appendChild(newDiv)
}