React类组件中如何获取被点击子组件以实现主图切换?
React类组件缩略图切换主图问题解决
你当前的核心问题是点击缩略图时没有将对应索引传递给父组件的切换函数,导致总容器组件的handlePictureChange无法获取点击项的信息。下面是具体的修改方案:
步骤1:修改单个缩略图组件,传递点击索引
在ProductSmallImage组件中,修改onClick事件,调用handlePictureChange时传入当前缩略图的索引(也就是id属性的值):
class ProductSmallImage extends Component { render() { return ( <> <SmallProductImage onClick={() => this.props.handlePictureChange(this.props.id)} src={this.props.imageSrc} alt={this.props.imageAlt} id={this.props.id} /> </> ) } }
步骤2:修改总容器组件,接收索引并更新主图状态
在ProductDetailPhotoGallery组件中,让handlePictureChange接收索引参数,并用该索引从productGal数组中获取对应图片,更新状态:
class ProductDetailPhotoGallery extends Component { state ={ imageSource: this.props.productGal[0] } handlePictureChange = (index) => { // 此时可以拿到点击的缩略图索引 console.log('点击的缩略图索引:', index); this.setState({ imageSource: this.props.productGal[index] }) } render() { return ( <ProductPhotoGalleryContainer> <ProductPageMiniatureImages productGal={this.props.productGal} handlePictureChange={this.handlePictureChange} /> <ProductPageDetailedImage imageSrc={this.state.imageSource} /> </ProductPhotoGalleryContainer> ) } }
说明
之前handlePictureChange里只能打印组件自身props,是因为点击事件没有传递任何点击相关的参数。通过在子组件点击时主动传递索引,父组件不需要获取整个子组件实例,直接用索引就能定位到对应的图片,实现主图切换的逻辑。
内容的提问来源于stack exchange,提问作者curiousRedReptile
相关产品推荐
相关产品推荐

