How to create dynamic refs in functional component- Using useRef Hook

蹲街弑〆低调 提交于 2021-02-18 13:52:55

问题


I want to have refs in functional component which have elements dynamically rendered.

please help me in creating Dynamic Refs using useRef Hook and accessing in the handler.

1) Need to create 3 useRefs to point 3 buttons.

2) Access them in button handler using "ref1.value" Or "ref2.value" etc

    let abc=[1,2,3];
 function submitclick(){
  alert(123);
// Here i want to access the buttons with using the refs
  }
  return ( <div>
  {  abc.map(function(index){ return (<button ref='123' onClick={submitclick}>{`Button${index}`}</button>)})}
    </div>);
};

ReactDOM.render(<MyComponent name="doug" />, document.getElementById('root'));```

回答1:


refs are basiclly objects, and they have a default key current. So, you can create an array of refs like this:

const myRefs= useRef([]);

Then you can populate this array of refs like this:

ref={el => (myRefs.current[i] = el)}

Here is the full version:

{
  [1, 2, 3].map((v, i) => {
    return (
      <button
        ref={(el) => (myRefs.current[i] = el)}
        id={i}
        onClick={submitClick}
      >{`Button${i}`}</button>
    );
  });
}


来源:https://stackoverflow.com/questions/57810378/how-to-create-dynamic-refs-in-functional-component-using-useref-hook

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