为React中唯一的一个元素添加类

时间:2018-07-16 10:12:02

标签: javascript reactjs list click toggle

我正在尝试在React中进行项目选择。您可以在下面看到我的代码。当我单击该项目时,它们都被选中,但是我的目标是仅单击那些我单击过的项目。我怎样才能做到这一点?我发现了同样的问题,但是我不知道该如何处理我的代码。

import React from "react";
import ReactDOM from "react-dom";
import prodList from "./prodList";

class RenderItem extends React.Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
    this.state = { addClass: false };
  }

  handleClick() {
    this.setState({ addClass: !this.state.addClass });
  }

  render() {
    return <div className="products-block">{this.renderItems()}</div>;
  }

  renderItems() {
    return prodList.map(this.renderItem.bind(this));
  }

  renderItem(product, i) {
    var someElementClass = this.state.addClass ? "clicked" : "";

    return (
      <div key={i}>
        <div className="products-block-item-card" onClick={this.handleClick}>
          <div className="products-block-item-card-decor">
            <div className="products-block-item-card-info">
              <div className="products-block-item-card-description">
                {someElementClass}
                {product.description}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您需要以某种方式跟踪单击的项目。为此,我们可以将单击的项目索引存储在状态变量clickedItem中。

...

class RenderItem extends React.Component {

constructor(props) {
    super(props)

    this.handleClick = this.handleClick.bind(this);
    this.state = {clickedItem: null};
}

handleClick(i) {
    this.setState({clickedItem: i});
}
render() {
    return <div className="products-block">
        { this.renderItems() }
    </div>;
}

renderItems() {
    return prodList.map(this.renderItem.bind(this))
}

renderItem(product, i) {
    var someElementClass = this.state.clickedItem === i ? 'clicked' : '';

    return <div key={i}>

        <div className="products-block-item-card" onClick={() this.handleClick(i)}>
            <div className="products-block-item-card-decor">
                <div className="products-block-item-card-info">
                    <div className="products-block-item-card-description">

                        {someElementClass}
                        {product.description}
                    </div>             
                </div>
            </div>
        </div>           
    </div>
}
}