React onClick将类添加到clicked元素,但从其他元素中删除 [英] React onClick add class to clicked element but remove from the others
本文介绍了React onClick将类添加到clicked元素,但从其他元素中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在这里想要实现的目标与在这里实现的目标非常相似 Flexbox中项目的过渡弹性增长
so what i try to achieve here is very similar to what is done here Transition flex-grow of items in a flexbox
但是我不知道如何用React说我有此代码
But what i wonder how this could be done with React say i have this code
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
classNameToUse: ''
};
this.onElementClicked = this.onElementClicked.bind(this);
}
onElementClicked() {
this.setState({ classNameToUse : 'big-size'})
}
render() {
return (
<div>
<div className={this.state.classNameToUse} onClick={this.onElementClicked} >
something
</div>
<div className={this.state.classNameToUse onClick={this.onElementClicked} >
something else
</div>
</div>
);
}
}
当然可以将className都添加到它们我想要实现的是,其中一个随着动画的发展而壮大,而另一个则崩溃了。如果我有2个或10个元素,就没关系了
This would of course add the className to them both but what i want to achieve is that one of them grows big with animation and the other collapse. And it sohuldnt matter if i have 2 or 10 elements
推荐答案
您可以在点击时设置活动索引:
You can set active index on click:
// State
this.state = {
activeIndex: null
};
// event
onElementClicked(e) {
this.setState({ activeIndex: e.target.index })
}
// class to use
className={this.index === this.state.activeIndex ? 'big-size' : ''}
这篇关于React onClick将类添加到clicked元素,但从其他元素中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文