本文介绍了如何在列表项上切换活动类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试在React中实现基本功能时遇到了问题。我有一个< img>
的列表,当我点击其中一个时,我想添加一个活动
类到这个img并从其他图像中删除这个类。
I'm having a issue in trying to implement a basic functionality in React. I have a list of <img>
, and when I click in one, I want to add an active
class to this img and remove this class from the other images.
class DefaultImages extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
console.log("Element:", e.target)
// I can add the class here, but where to remove from the other images?
}
render() {
var imgSize = "100"
return (
<div>
<img onClick={this.handleClick} src="img/demo.png" width={imgSize} height={imgSize} />
<img onClick={this.handleClick} src="img/demo2.png" width={imgSize} height={imgSize} />
<img onClick={this.handleClick} src="img/demo3.jpg" width={imgSize} height={imgSize} />
<img onClick={this.handleClick} src="img/demo4.png" width={imgSize} height={imgSize} />
</div>
)
}
}
我知道如何从点击的图像中切换班级,但是如何从兄弟姐妹图像中删除活动类?
I know how to toggle the class from the clicked image, but how can I remove the active class from the siblings images?
推荐答案
使用组件的状态
存储活动项目并在视图发生变化时重新呈现:
Use the component's state
to store the active item and rerender the view when it changes:
import React, { Component } from 'react'
const IMG_SIZE = 100
const imgs = [{ id: 1, src: 'img/demo.png' }, { id: 2, src: '...' }, etc]
class DefaultImages extends Component {
constructor() {
this.state = { activeItem: {} }
this.toggleActiveItem = this.toggleActiveItem.bind(this)
}
toggleActiveItem(imgId) {
this.setState({ activeItem: { [imgId]: true } })
}
render() {
return (
<div>
{imgs.map(img =>
<img
className={this.state.activeItem[img.id] ? 'active' : ''}
onClick={e => this.toggleActiveItem(img.id)}
src={img.src}
width={IMG_SIZE}
height={IMG_SIZE}
alt={`Default image ${img.id}`}
/>
)}
</div>
)
}
}
这篇关于如何在列表项上切换活动类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!