【问题标题】:How to toggle an active class on list items?如何在列表项上切换活动类?
【发布时间】:2017-05-01 11:31:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript html css reactjs ecmascript-6


    【解决方案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>
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多