React Ref:对象数组的 Ref 函数仅记录第 1 项



我通过来自外部API的对象数组进行映射,该数组成功显示其内容。我现在正在尝试通过 React ref 访问他们的个人 clientHeights,但当我登录到我的控制台时,它似乎只输出第一项:


class ImageList extends React.Component{
constructor(props){
super(props)
this.imageRef = React.createRef()

}

componentDidMount(){
console.log(this.imageRef)
}


render(){

const images= this.props.images.map((image)=>{

return( 
<img ref={this.imageRef}
key={image.id} 
src={image.urls.regular}
alt={image.description} />
)})


return(
<div  className="image-list" >
{images}
</div>

)

}


}

我试图获得他们所有的客户高度,而不仅仅是第一个。谢谢

您的代码会将每个 img 节点分配给this.imageRef。我不确定为什么它保留第一个引用,但无论哪种方式,它都不会像您期望的那样工作。要获取 img 节点数组,您需要将 ref 设置为数组并将每个节点添加到其中。ref道具可以是一个函数,所以尝试这样的东西

class ImageList extends React.Component{
constructor(props){
super(props)
}

componentDidMount(){
console.log(this.imageRefs)
}


render(){
this.imageRefs = []

const images= this.props.images.map((image)=>{

return( 
<img ref={ref => {this.imageRefs.push(ref)}}
key={image.id} 
src={image.urls.regular}
alt={image.description} />
)})


return(
<div  className="image-list" >
{images}
</div>

)

}


}

我得到的另一种方法(从教程中获得)是将图像及其内容显示为另一个组件(称之为ImageCard-我现在放置 ref 的地方),然后显示该组件代替原始<img/>标签,如下所示:

class ImageList extends React.Component{



render(){


const images= this.props.images.map((image)=>{

return( 
<ImageCard key={image.id} image= {image}/>
)})

console.log(images);
return(
<div  className="image-list" >
{images}
</div>

)

}


}

这使得对 ImageCard 组件所做的任何操作也会通过映射。 顺便说一句,我现在刚看完这个

最新更新