In react how to get ref of first element that's rendered from Map

雨燕双飞 提交于 2019-12-05 18:43:39

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!