简体   繁体   English

如何在 React/typescript 中访问嵌套 DOM 元素的文本值

[英]How to access text value of nested DOM element in React/typescript

What would be the best way to access a nested div text value: It needs to be clickable on the parent div.访问嵌套 div 文本值的最佳方法是什么:它需要在父 div 上可点击。

<div className='Outer'>
   <div className='Inner'>
      <p className='value'>Text Value</p>
   </div>
</div>

I want to access the text of value = 'Text Value';我想访问 value = 'Text Value' 的文本;

I have thought of passing the event into the function something like:我想过将事件传递给函数,例如:

const handleProps = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault();
    console.log(e.currentTarget)
}

But this gives a list of DOM nodes and I'm not sure if thats the best way in React?但这给出了一个 DOM 节点列表,我不确定这是否是 React 中的最佳方式?

I have thought of Refs but from what I can see that is more for inputs etc, unless I have misunderstood.我已经想到了Refs但从我所见,更多的是用于输入等,除非我误解了。

import {useRef} from React;

...
const pValue = useRef("");

...
<p ref={pValue} className='value'>Text Value</p>

...
// when can take value: innerHtml, textContent or innerText
console.log(pValue.current);//element
console.log(pValue.current.textContent);


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

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