如何在响应中应用classNames来更改React

时间:2016-07-14 05:30:30

标签: html css reactjs class-names

我有3个孩子divs包裹在一个父div中,如下所示:

enter image description here

点击每个孩子div,我希望将其背景颜色更改为红色。但如果已经有一个div背景颜色为红色,而其他一些div被点击,则其背景颜色应更改为白色。只有一个div背景色为红色。我是新手做出反应。我在React中了解了classNamesstates,但无法知道如何执行此操作。

jsfiddle

先谢谢。

2 个答案:

答案 0 :(得分:4)

你可以做你想做的事情



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')
);
&#13;
.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;
  }
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我建议你试试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.