简体   繁体   English

反应如何设置组件ID以能够使用document.getElementById()

[英]React how to set component id to be able to use document.getElementById()

I have read a few questions, and I thought that just setting the id like the following should work: 我已经阅读了几个问题,我认为只需要像下面那样设置id就可以了:

<MyComponent id="myId"/>

But when I call document.getElementById() on the id, I get null and when I inspect the page, the component has an empty id. 但是,当我在id上调用document.getElementById() ,将得到null并且当我检查页面时,该组件具有一个空ID。

What am I missing? 我想念什么?

As @Lekhnath mentioned your MyComponent root elements id can be used to access the component. 如@Lekhnath所述,您的MyComponent根元素ID可用于访问组件。 Something like below where you can access element with "componentId": 如下所示,您可以使用“ componentId”访问元素:

class MyComponent extends Component{
  render(){
  return <div id="componentId">
             ...your child component details here
         </div>
  }
}

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

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