【问题标题】:How to get the ref of the first element that's rendered with .map?如何获取使用 .map 呈现的第一个元素的 ref?
【发布时间】:2018-05-28 22:29:26
【问题描述】:

我需要在几行中显示视频(卡片)的缩略图,并专注于第一个缩略图。我使用嵌套地图进行了显示。该代码基本上遍历一个视频数组并返回多行视频。

我们如何专注于渲染的第一个元素?我认为我们需要获得第一个元素的 ref 来关注。但是我们如何在这里设置 ref 并在另一个函数中引用它呢?

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>
  );
}

【问题讨论】:

  • 也许将其设置在查找表中? ref =&gt; this.videosRefs[key] = ref?

标签: javascript reactjs ref


【解决方案1】:

Hello react hook here 我希望这可以帮助您使用 tabIndex 定位第一个元素。

    const elementRef = useRef();

    useEffect(() => {

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

            elementRef.current.click();

        }

    }, []);


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

        </div>

    )

【讨论】:

    【解决方案2】:

    也许使用查找表对象或数组,并通过索引(或 id)存储所有参考。
    然后当组件被挂载时,您可以在第一个(或任何其他通过 key 或 id 的)上触发焦点事件。

    带输入的简单示例:

    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>

    【讨论】:

    • 相当不错的解决方案:)
    猜你喜欢
    • 2015-03-31
    • 2012-06-22
    • 2014-09-08
    • 2018-09-02
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    相关资源
    最近更新 更多