简体   繁体   中英

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 className='Outer'>
   <div className='Inner'>
      <p className='value'>Text Value</p>
   </div>
</div>

I want to access the text of 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?

I have thought of Refs but from what I can see that is more for inputs etc, unless I have misunderstood.

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);


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