You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 02:03:19