简体   繁体   English

如何使用 useRef Hook 访问 div 的内部内容或 reactjs 中的任何元素?

[英]How to access inner content of div or any element in reactjs using useRef Hook?

First of all Greeting from my side I am beginner in Reactjs and I am learning a new hook called useRef() hook.首先从我这边问候我是 Reactjs 的初学者,我正在学习一个名为 useRef() 钩子的新钩子。 Basically I am trying to fetch the content of every element present in my div using useRef Hook.基本上,我正在尝试使用 useRef Hook 获取 div 中存在的每个元素的内容。 In my code I need to access the content of only p tag how can I achieve it?在我的代码中,我只需要访问 p 标签的内容,我该如何实现呢? This is my Code:-这是我的代码:-

import React,{useRef} from 'react'

function FormData() {
    const getAllData = useRef(null)

    const onClickHandler = () =>{
        console.log(getAllData.current) 
    }
    
  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

Ok so if you just need to access the P tag.好的,如果您只需要访问 P 标签。 then you can modify your OnlickHandler something like this.然后你可以像这样修改你的 OnlickHandler 。

const onClickHandler = () => {
 console.log(getAllData.current.children[1].innerText);
};

you can access the current elements' child properties by going through its indexes.您可以通过其索引访问当前元素的子属性。 So in that case your P tag lies on the 1st index so you can just do and you'll get the P tag.所以在这种情况下,你的 P 标签位于第一个索引上,所以你可以这样做,你会得到 P 标签。

.children[index]

getAllData.current now is an element object . getAllData.current现在是一个element object list of properties and methods属性和方法列表
you can access its children via children property.您可以通过children属性访问其子项。

const onClickHandler = () => {
    const list = getAllData.current.children;
    for (const e of list) {
      if (e.tagName === "P") {
        console.log(e.textContent);
      }
    }
  };

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

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