多个图像轮播效果很好,但是我想向轮播中的每个图像添加onClick事件处理程序,并将其呈现在轮播的顶部,并且仅对每张幻灯片的第一个元素起作用,而对其余元素不起作用在活动幻灯片中。
我已经通过自定义多图像轮播实现了该功能,请查看下面的代码。
interface imgprops {
AdListItem: any;
}
class Imageslide extends Component<imgprops, any> {
constructor(props: any) {
super(props);
this.state = { imgsrc: this.props.AdListItem[0].src };
}
componentDidMount() {
$('.multi-item-carousel .item').each(function(){
var next = $(this).next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
for (var i=0;i<2;i++) {
next=next.next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
}
});
}
public DisplayImage(details: any) {
debugger;
this.setState(
this.state = { imgsrc: details.src }
);
console.log(this.state);
}
render() {
debugger;
return (
<div className="ms-Grid-row">
<div className="card">
<div className='ProdImgView'>
<img src={this.state.imgsrc} alt="avengers" className='prodimg' />
<div className="prodprize">
<p className="card-prize"><i className="fas fa-rupee-sign"></i>{this.props.AdListItem.prize}</p>
</div>
</div>
</div>
<div className="ms-Grid-col ms-sm6 ms-md4 ms-lg12 ImageslideMainDiv">
<div className="carousel slide multi-item-carousel" id="theCarousel">
<div className="carousel-inner">
<div className="item active">
<div className="ms-Grid-col ms-sm3"><img src={this.props.AdListItem[0].src} className="img-responsive" onClick={() => { debugger; this.DisplayImage(this.props.AdListItem[0]) }} /></div>
</div>
{this.props.AdListItem.map((items: any) =>
<div className="item">
<div className="ms-Grid-col ms-sm3"><img src={items.src} className="img-responsive" onClick={() => { debugger; this.DisplayImage(items) }} /></div>
</div>
)}
</div>
<a href="#theCarousel" className="left carousel-control left" data-slide="prev">
<i className="fas fa-chevron-left ChevronIcon"></i>
</a>
<a href="#theCarousel" className="right carousel-control right" data-slide="next">
<i className="fas fa-chevron-right ChevronIcon"></i>
</a>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state: any) {
return {
AdListItem: state.AdList
};
}
export default connect(mapStateToProps, undefined)(Imageslide);
我想渲染被单击到轮播顶部的每个元素。 但是只有轮播中的每个第一个元素都以正确的方式工作,有人才能为我找出答案。
答案 0 :(得分:1)
您必须将功能绑定到组件,然后问题才能解决。
将以下行添加到构造函数中,
constructor(props: any) {
super(props);
this.state = { imgsrc: this.props.AdListItem[0].src };
// New line
this.DisplayImage = this.DisplayImage.bind(this);
}