最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the ref of the first element that's rendered with .map? - Stack Overflow

programmeradmin5浏览0评论

I have a requirement to show thumbnails of videos(cards) in several rows and focus on the very first thumbnail. I did the display using Nested Map. The code basically iterates over a videos array and returns videos in several rows.

How do we focus on the first element that renders? I think we need to get ref of the first element to focus. But how do we set ref here and reference it in another function?

const CategoryGrid = props => {
  return (
    <HotKeys handlers={handlers}>
      <div className="grid-container">
        <p className="title"> {props.title.toUpperCase()} </p>
        <div className="grid">
          {
            props.videos.map((rowvideos,index) => {
                var rowVideoArr = [];
                rowvideos.map((video,key)=>{
                  rowVideoArr.push(<div  key={video.id} className="fleft card-container grow">
                    <Card key={video.id} title={video.name} background={video.thumbnailUrl}/>
                  </div>)
                })
                return(<div className="row" key={index}>{rowVideoArr}</div>)
            })
          }
        </div>
      </div>
    </HotKeys>
  );
}

I have a requirement to show thumbnails of videos(cards) in several rows and focus on the very first thumbnail. I did the display using Nested Map. The code basically iterates over a videos array and returns videos in several rows.

How do we focus on the first element that renders? I think we need to get ref of the first element to focus. But how do we set ref here and reference it in another function?

const CategoryGrid = props => {
  return (
    <HotKeys handlers={handlers}>
      <div className="grid-container">
        <p className="title"> {props.title.toUpperCase()} </p>
        <div className="grid">
          {
            props.videos.map((rowvideos,index) => {
                var rowVideoArr = [];
                rowvideos.map((video,key)=>{
                  rowVideoArr.push(<div  key={video.id} className="fleft card-container grow">
                    <Card key={video.id} title={video.name} background={video.thumbnailUrl}/>
                  </div>)
                })
                return(<div className="row" key={index}>{rowVideoArr}</div>)
            })
          }
        </div>
      </div>
    </HotKeys>
  );
}
Share Improve this question edited Apr 21, 2020 at 15:13 Flip 6,7618 gold badges50 silver badges83 bronze badges asked Dec 14, 2017 at 18:36 prasadmsvsprasadmsvs 1,7394 gold badges19 silver badges31 bronze badges 1
  • maybe set it inside a lookup table? ref => this.videosRefs[key] = ref? – Sagiv b.g Commented Dec 14, 2017 at 18:41
Add a comment  | 

2 Answers 2

Reset to default 15

Maybe use a lookup table object or an array and store all the refs there by their index (or id).
Then when the component is mounted, you can trigger the focus event on the first one (or any other one by the key or id).

Simple example with inputs:

const videos = [
  { name: 'video 1' },
  { name: 'video 2' },
  { name: 'video 3' },
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.videoRefs = [];
  }

  componentDidMount() {
    this.videoRefs[0] && this.videoRefs[0].focus();
  }

  render() {
    return (
      <div >
        {
          videos.map((video, index) => (
            <input
              key={index}
              value={video.name}
              ref={ref => this.videoRefs[index] = ref}
            />
          ))
        }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Hello react hook here I hope this helps you can target the first element using tabIndex.

    const elementRef = useRef();

    useEffect(() => {

        if (elementRef.current.tabIndex === 0) {

            elementRef.current.click();

        }

    }, []);


    return (
        
        <div tabIndex={index} ref={elementRef} id={`${activeLink === index ? "selected" : ""}`}

        </div>

    )
发布评论

评论列表(0)

  1. 暂无评论