You need to enable JavaScript to run this app. React循环场景下同一集合存储多个callback ref的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

React循环场景下同一集合存储多个callback ref的实现方法

更新:我认为下述是在循环中设置多个引用的正确实现方式。如果存在可使用回调函数替代该实现的其他方案,我会后续补充,谢谢。

以下是参考实现代码:

class demo2 extends React.Component {
  constructor(props) {
    super(props);
    this.elements = ["Alex", "Is", "A", "Psycho"];
    this.inputRefs = [];
  }

  printName = (key) => {
    alert(this.inputRefs[key].innerText);
  }

  render() {
    return (
        <div>
            {this.elements.map((v, key) => {
                return (
                    <div>
                        <p ref={ref => (this.inputRefs[key+'-name'] = ref)}>Name 1: {v}</p>
                        <p ref={ref => (this.inputRefs[key+'-name2'] = ref)}>Name 2: {v}</p>
                        <br></br>
                        <button onClick={() => this.printName(key+'-name')}> Alert name 1 </button>
                        <button onClick={() => this.printName(key+'-name2')}> Alert name 2 </button>
                    </div>
                )
            })}
        </div>
    )
  }
}

内容的提问来源于stack exchange,提问作者Johnathan M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:48:09