如何在列表项上切换活动类?

IT技术 javascript html css reactjs ecmascript-6
2021-04-27 01:19:13

我在尝试在 React 中实现基本功能时遇到问题。我有一个 的列表<img>,当我单击其中一个时,我想active向这个 img添加一个类,并从其他图像中删除这个类。

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>
    )
  }
}

我知道如何从单击的图像中切换类,但是如何从兄弟图像中删除活动类?

1个回答

使用组件的state来存储活动项并在更改时重新渲染视图:

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>
    )
  }
}