如何在ReactJS中使用useRef Hook获取指定p标签的内容?
获取div下p标签内容的方法
你可以利用DOM API的querySelector或querySelectorAll方法,从useRef指向的div元素中筛选出p标签,进而获取其内容。
单个p标签的情况
如果你的div下只有一个p标签,直接用querySelector('p')定位,再通过textContent获取内容:
import React,{useRef} from 'react' function FormData() { const getAllData = useRef(null) const onClickHandler = () =>{ // 获取单个p标签元素 const pElement = getAllData.current.querySelector('p'); // 获取p标签的文本内容 if(pElement) { console.log(pElement.textContent); } } return ( <div ref={getAllData} > <h1>UseRef Tutorial</h1> <p>Abhishek Poddar</p> <input type="email" placeholder='Enter the Email' /> <br></br> <br></br> <input type="password" placeholder='Enter the Password' /> <br></br> <br></br> <button onClick={onClickHandler}>Click Me</button> </div> ) } export default FormData
多个p标签的情况
如果div下有多个p标签,用querySelectorAll('p')获取所有p标签节点列表,再遍历获取每个的内容:
import React,{useRef} from 'react' function FormData() { const getAllData = useRef(null) const onClickHandler = () =>{ // 获取所有p标签元素 const pElements = getAllData.current.querySelectorAll('p'); // 遍历获取每个p标签的文本内容 pElements.forEach(p => { console.log(p.textContent); }); } return ( <div ref={getAllData} > <h1>UseRef Tutorial</h1> <p>Abhishek Poddar</p> <p>Another Paragraph</p> <input type="email" placeholder='Enter the Email' /> <br></br> <br></br> <input type="password" placeholder='Enter the Password' /> <br></br> <br></br> <button onClick={onClickHandler}>Click Me</button> </div> ) } export default FormData
说明
querySelector('p')会返回div下第一个匹配的p标签元素querySelectorAll('p')会返回div下所有匹配的p标签组成的NodeList,需要遍历处理- 加上
if(pElement)的判断是为了避免组件挂载前调用handler导致的null报错,保证代码健壮性
内容的提问来源于stack exchange,提问作者Abhishek Poddar
相关产品推荐
相关产品推荐

