我正在使用数组映射函数
渲染React组件//I need to access the element here
elements.map( element => {
//And here
return <Sample ref = { e => this.myRef = e} />
}
当我尝试访问this.myRef时,它返回undefined。访问<Sample/>
的DOM对象的正确方法是什么?
答案 0 :(得分:1)
映射可以遍历多个索引,每次迭代时都会覆盖this.myRef,并且最终迭代结束时的this.myRef将仅包含最后一个索引。请找到有用的代码段。
constructor(){
//Initialise this.myRef to be an array.
this.myRef = [];
}
//Somewhere when u r iterating
elements.map( (element,index) => {
//Expecting you already imported React
this.myRef[index] = React.createRef();
return <Sample ref = { this.myRef[index] } />
})
//Now log it here just to confirm
console.log(this.myRef);