Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 获取循环列表 ref #46

Open
jtwang7 opened this issue May 3, 2022 · 0 comments
Open

React 获取循环列表 ref #46

jtwang7 opened this issue May 3, 2022 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented May 3, 2022

React 获取循环列表 ref

参考文章:react获取循环列表的ref

使用场景

react 项目中有时会需要用到 ref 去获取节点的真实 dom 对象,在函数组件中官方推荐使用 useRef。
当前,我在渲染列表时想获取所有li的dom元素,同时将这些 dom refs 保存在一个 ref 列表中做相同的逻辑处理。

解决方案

利用 React 的 React.forward 以及回调ref

import React, { useRef } from 'react';

export default function Demo() {
  const list = [1, 2, 3, 4, 5];
  const liRefList = useRef([]); // 保存 refs
  return (
    <ul>
      {
        list.map(item => {
          // (ref) => {xxx} : 回调ref
          return <li ref={(ref) => {liRefList.current.push(ref)}} key={item} id={'my-list-item' + item}>{item}</li>
        })
      }
    </ul>
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant