我想为 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在这两种情况下都会出现此错误。
2 回答
忽然笑
TA贡献1806条经验 获得超5个赞
你需要将引用存储在数组中
class Component {
let _refs = [];
displayXmasTreeParts = () => Array(40).fill().map((el, index) => {
_refs = [];
return (
<div className={`xmasTreePart${randomClass}`} key={`part${index}`}
ref={el => _refs.push(el)}/>
);
}
...
}
添加回答
举报
0/150
提交
取消