如何在 React 中应用 classNames 以更改 React 中 child div 之一的背景颜色

How can I apply classNames in react to change the background color of one of the child div in React

我有3个children divs包在一个parent div中,如图:

单击每个 child div,我希望将其 background-color 更改为红色。但是如果已经有一个 div 带有 background-color 红色并且单击了其他一些 div 那么它的背景颜色应该更改为白色。只有一个 div 背景颜色为红色。我是新手反应。我在 React 中阅读了 classNamesstates,但无法找到我该怎么做。

jsfiddle

提前致谢。

我建议你试试 jQueryToggle。


    $(document).ready(function(){
        $("button").click(function(){
            $("p").toggleClass("main");
        });
    });


    Toggle class "main" for p elements

    

This is a paragraph.

This is another paragraph.

Note: Click the button more than once to see the toggle effect.

你可以随心所欲

var Сards = React.createClass({
  getInitialState: function () {
    return {
      cards: [
       { name: 'сard 1', isActive: false },
        { name: 'сard 2', isActive: false },
        { name: 'сard 3', isActive: false }
      ]
    };
  },
  
  handleClick: function (index) {
    const cards = this.state.cards.map((card, i) => {
      card.isActive = i === index ? true : false;
      return card;
    })
    
    this.setState({ cards })
  },
  
  render: function() {
    const cards = this.state.cards.map((card, index) => {
      return <div 
       key={ index } 
        className={ 
          card.isActive 
            ? 'cards__card cards__card_active' 
            : 'cards__card'
        }
        onClick={ () => this.handleClick(index) }
      >
        { card.name }
      </div>
    });
    
    return <div className="cards">
      { cards }
    </div>;
  }
});

ReactDOM.render(
  <Сards />,
  document.getElementById('container')
);
.cards {
  border: 1px solid #000;
  padding: 5px;
}

.cards__card {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  margin: 5px;
  cursor: pointer;
  display: inline-block;
}

  .cards__card_active {
    background: red;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>