在 ReactJS 中使用 this 动态变量名

我想为 40 个 div 创建多个引用而不使用React.createRef(). 但我无法为我的引用创建动态变量名称。我正在使用下面的代码来创建参考。


const displayXmasTreeParts = () => Array(40).fill().map((el, index) => (

  <div className={`xmasTreePart${randomClass}`} key={`part${index}`} 

     ref={el => [this.el`${index}`] = el}/>

);


const handleClick = () => this.el5.classList.add(`new-class`);


render() {

  return (

    <div className="xmasTree">

      {this.displayXmasTreeParts()}

    </div>

    <button className="SetUpTree" onClick={this.handleClick}>Click here to reveal Our Xmas Tree</button>

)}

我也尝试过这个ref={el => `this.el${index}` = el}


但Invalid left-hand side in assignment expression在这两种情况下都会出现此错误。


繁星淼淼
浏览 80回答 2
2回答

拉风的咖菲猫

怎么样ref={el&nbsp;=>&nbsp;{this["el"+index]&nbsp;=&nbsp;el}}/>

忽然笑

你需要将引用存储在数组中class Component {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; let _refs = [];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; displayXmasTreeParts = () => Array(40).fill().map((el, index) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; _refs = [];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div className={`xmasTreePart${randomClass}`} key={`part${index}`}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ref={el => _refs.push(el)}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ...&nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript