简体   繁体   中英

React. Cannot get the component element in the DOM

I'm trying to insert the innerHTML for the div container ed . But I cannot get it after the React has render it. I understand that it's the problem with the stages of render, because I get null for this div container. What is I'm making the wrong?

class Test extends React.Component {
  render() {
    return (
      <div> 
        <div id='ed'>
        <p>{this.props.prop.text}</p>
        </div> 
        {document.querySelector('#ed').innerHTML = this.props.prop[1]} // this the problem
      </div> 
    );
  }
}

ReactDOM.render(
  <Test prop={store.getState()} />,
  document.getElementById('root')
);

Your direct DOM manipulation won't work cause you called it in render().

You called Query selector in render(), Query selector or findDOMNode() only works on mounted components (that is, components that have been placed in the DOM).

If you try to call this on a component that has not been mounted yet (like calling Query selector or findDOMNode() in render() on a component that has yet to be created) an exception will be thrown.

you can do expressions in render() usually, but you can't get access the DOM element in render() since it is placing your elements in render() to DOM.

Use lifeCycle methods instead and You can use ReactDOM.findDOMNode(this) to access the underlying DOM node. But accessing the DOM node and manipulating like you do is against the React style of programming.

Query selector shouldn't be necessary with react just attach a ref to the element you want and you have access to it within any function of the react component.

Example Demo : demo

Try using the lifecycle event componentDidMount

class Test extends React.Component {
  componentDidMount() {
    const element = document.querySelector('#ed');
    if (element) {
      element.innerHTML = this.props.prop[1]
    }
  }
  render() {
    return (
      <div> 
        <div id='ed'>
          <p>{this.props.prop.text}</p>
        </div> 
      </div> 
    );
  }
}

You need to wait for the component to mount. You can do this by putting your code in a componentDidMount method.

componentDidMount() {
    document.querySelector('#ed').innerHTML = "woo"
}

You may also reference the container div with ref={node => this.node = node}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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