我有3个孩子divs
包裹在一个父div
中,如下所示:
点击每个孩子div
,我希望将其背景颜色更改为红色。但如果已经有一个div
背景颜色为红色,而其他一些div
被点击,则其背景颜色应更改为白色。只有一个div
背景色为红色。我是新手做出反应。我在React中了解了classNames和states
,但无法知道如何执行此操作。
先谢谢。
答案 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;
答案 1 :(得分:0)
我建议你试试jQueryToggle。
$(document).ready(function(){ $("button").click(function(){ $("p").toggleClass("main"); }); });
Toggle class "main" for p elementsThis is a paragraph.
This is another paragraph.
Note: Click the button more than once to see the toggle effect.