【发布时间】:2023-03-31 22:30:01
【问题描述】:
我正在使用 React 类组件制作产品展示网页,页面中有两个部分,一个是产品缩略图区域(左),另一个是产品的大全图(右),目前看起来像这:
我希望当用户点击缩略图时,主大图应该相应地更改为相同的缩略图。
JSX
//React, css and all the images import
//contains all the thumbnail variable
var thumbs = [t1, t2, t3, t4];
//Contains the Larger image in the same index order
var model = [b1, b2, b3, b4];
export default class Display extends Component {
constructor() {
super();
this.state = {
modelImage: model[0] //initially a default 1st image is to be shown
};
}
render() {
return (
<div>
<Navbar />
<div className="model">
//Thumbnails
<div className="model-thumb">
{
// I suspect error on this line below
thumbs.map((thumb, index) =>
<img src={thumb}
key={index}
alt="Product-thumb"
width="75px"
onClick={ (index) => {
// Error on this line below(maybe)
this.setState({modelImage: model[index]})
//logs the image first time but after then always undefined
console.log(this.state.modelImage)
}
} />
)
}
</div>
<div className="model-image">
// Big Image
<img src={this.state.modelImage} alt="Product-image" />
</div>
</div>
</div>
)
}
}
在搜索各种答案的过程中,我发现这与范围有关,应该使用bind(),但我不太了解this和范围的概念以及如何实现@987654326 @在我的情况下,如果是这种情况,请帮助我或在这里向我提出问题。
提前谢谢你。
【问题讨论】:
-
您可能会惊喜地发现
console.log(this)的战略位置可以帮助您了解正在发生的事情。 -
@Wyck 是的,我知道至少状态正在改变,但未定义。
标签: javascript reactjs jsx