我正在使用数组映射函数渲染 React 组件
//I need to access the element here
elements.map( element => {
//And here
return <Sample ref = { e => this.myRef = e} />
}
当我尝试访问 this.myRef 时,它返回未定义。访问 DOM 对象的正确方法是什么<Sample/>
?
映射可以遍历多个索引,每次迭代时都会覆盖 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);