简体   繁体   English

无法访问React Typescript中的DOM元素

[英]Can't access DOM elements in React Typescript

I am making an application with a table where the rows expand when clicked on. 我正在创建一个带有表的应用程序,单击该表时行会扩展。 I have implemented the expansion of rows already (I am using a very similar idea as this link ). 我已经实现了行的扩展(我正在使用与此链接非常相似的想法)。

Based on the referred link above, in the expanded rows (under line 43), I want to add a <div> element with id={item.id} . 基于上面引用的链接,在扩展行中(第43行下方),我想添加一个id={item.id}<div>元素。 Then just before we exit the if block, I want to send that <div> element I just made with id={item.id} to an external method (eg. an external API). 然后,在我们退出if块之前,我想将刚才用id={item.id}制作的<div>元素发送到外部方法(例如,外部API)。

Right now, I am trying to do document.getElementById(item.id) but it returns undefined . 现在,我正在尝试执行document.getElementById(item.id)但它返回undefined I also tried using refs, but was getting the same problem. 我也尝试使用refs,但是遇到了同样的问题。

The thing is, if I move the <div> element to let's say the render method, everything works fine. 关键是,如果我将<div>元素移动到render方法,那么一切都会正常。 It's just here that I'm having troubles accessing the DOM element. 就在这里,我在访问DOM元素时遇到了麻烦。

Does anyone know where I'm going wrong? 有谁知道我要去哪里错了?

JSFiddle: https://jsfiddle.net/n5u2wwjg/101051/ JSFiddle: https ://jsfiddle.net/n5u2wwjg/101051/

Use React's refs to capture the DOM element, and access that DOM in componentDidMount(). 使用React的ref捕获DOM元素,并在componentDidMount()中访问该DOM。 The DOM you're referring to in render() method is React's virtual DOM, and at the time render method was called first time, it's not actually display on the browser yet, that's why document.getElementById return undefined 您在render()方法中引用的DOM是React的虚拟DOM,并且在第一次调用render方法时,它实际上尚未显示在浏览器上,这就是为什么document.getElementById返回undefined的原因

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

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