简体   繁体   English

使用 React Hooks 引用 DOM 元素

[英]Referencing DOM Elements with React Hooks

I'm creating references to DOM elements in order to use React Hooks for functional components like so:我正在创建对 DOM 元素的引用,以便将 React Hooks 用于功能组件,如下所示:

        let link1, link2 = useRef();

        <ul>
            <li>
               <a ref={element => { link1 = element;}}>FAQ</a>
            </li>
            <li>
               <a ref={element => { link2 = element;}}>Contact Us</a>
            </li>
        </ul>

Question is, do I have to create references for every DOM element I want to target like the above?问题是,我是否必须像上面那样为我想要定位的每个 DOM 元素创建引用? I feel the code will grow quick.我觉得代码会增长得很快。

Here's the codepen for complete code.这是完整代码的代码

You could alternatively create one ref for the parent element of all the elements that are related and crawl the node from there.您也可以为所有相关元素的父元素创建一个引用,并从那里抓取节点。

If you change your schema to:如果您将架构更改为:

const ulRef = useRef(null);
<ul ref={ulRef}>
        <li>
           <a className="link">FAQ</a>
        </li>
        <li>
           <a className="link">Contact Us</a>
        </li>
    </ul>

You can crawl the nodes like this: 您可以像这样抓取节点:

 
 
 
  
  ulRef.current.children().children('a')
 
 

Which should return a nodeList of all of your links. 这应该返回所有链接的 nodeList 。 ^This was using a jQuery syntax that is still stuck in my head from years back.... ^这是使用 jQuery 语法,多年前它仍然停留在我的脑海中......

You can use this command to create an HTMLCollection of your li nodes: ulRef.current.children , then iterate over them for the values you are wanting.您可以使用此命令创建 li 节点的ulRef.current.childrenulRef.current.children ,然后遍历它们以获得您想要的值。

I created a simplified example on codesandbox .我在codeandbox上创建了一个简化示例。

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

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