【问题标题】:How to create dynamic refs in functional component- Using useRef Hook如何在功能组件中创建动态引用 - 使用 useRef Hook
【发布时间】:2020-01-08 15:28:56
【问题描述】:

我想在功能组件中拥有动态呈现元素的引用。

请帮助我使用 useRef Hook 创建动态引用并在处理程序中访问。

1) 需要创建 3 个 useRefs 来指向 3 个按钮。

2) 使用“ref1.value”或“ref2.value”等在按钮处理程序中访问它们

    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'));```

【问题讨论】:

  • 你尝试了什么?你读过文档吗?
  • 为什么首先需要useRef

标签: reactjs react-hooks


【解决方案1】:

refs 基本上是对象,它们有一个默认键 current。因此,您可以像这样创建一个 refs 数组:

const myRefs= useRef([]);

然后你可以像这样填充这个引用数组:

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

这是完整版:

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

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 2021-12-25
    • 2021-02-27
    • 2021-06-11
    • 2021-06-22
    • 2020-02-17
    • 1970-01-01
    • 2020-12-05
    • 2020-08-06
    相关资源
    最近更新 更多