我使用react-slick輪播與自定義控件。我只想添加'活動'類到更改幻燈片的元素(通過onClick事件)。但在我的情況下,「積極」的班級切換所有人。將類添加到React onClick中的特定元素
export default class ServicesSlider extends React.Component {
constructor(props) {
super(props)
this.changeSlide = this.changeSlide.bind(this)
this.state = {
isActive: false
}
}
changeSlide(e) {
this.setState({
isActive: !this.state.isActive
});
this.slider.slickGoTo(e);
}
render() {
return (
<div>
<section className="carousel-controls">
<div
onClick={() => this.changeSlide(0)}
className={this.state.isActive
? 'column' : 'column active'}>Slide one
</div>
<div
onClick={() => this.changeSlide(1)}
className={this.state.isActive
? 'column' : 'column active'}>Slide two
</div>
<div
onClick={() => this.changeSlide(2)}
className={this.state.isActive
? 'column' : 'column active'}>Slide three
</div>
<div
onClick={() => this.changeSlide(3)}
className={this.state.isActive
? 'column' : 'column active'}>Slide four
</div>
</section>
<Slider ref={c => this.slider = c}>
<div className="sliderItem">Slide 1</div>
<div className="sliderItem">Slide 2</div>
<div className="sliderItem">Slide 3</div>
<div className="sliderItem">Slide 4</div>
</Slider>
</div>
)
}
}
如何正確追加類到React中的特定元素?
保持活躍類的,而不是一個單一的國家 –
你傳遞一個索引changeSlide,但只有切換活動狀態的狀態數組。因此狀態將是一個布爾值,true或false,而不是表示當前活動元素的整數 – Matthew