2016-12-15 12 views
2

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

私がクリックした画像からクラスをトグルする方法を知っているが、どのように私は兄弟画像からアクティブなクラスを削除することができますか?

答えて

4

は、アクティブな項目を格納し、それが変化したときにビューを再描画するために、コンポーネントの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> 
    ) 
    } 
}