[英]remove class from all other elements when adding class
I have this component: 我有这个组成部分:
class NavTree extends React.Component {
// This is the left nav tree that opens each group for editing
constructor(props) {
super(props);
this.state = {
activeGroup: null // use this value to highlight the nav item in the tree
};
this.activateGroup = this.activateGroup.bind(this);
}
activateGroup(event) {
this.setState({activeGroup: event.target.id});
this.props.onNavChange(event.target.id);
event.target.className = "active"; // this works
}
render() {
return (
<React.Fragment>
<div id="nav" className="col-2">
<ul>
<li id="discovery" onClick={this.activateGroup}>Discovery</li>
<li id="financial" onClick={this.activateGroup}>Financials</li>
<li id="sales_stuff" onClick={this.activateGroup}>Sales Stuff</li>
</ul>
</div>
</React.Fragment>
);
}
}
This code works: event.target.className = "active";
这段代码有效:
event.target.className = "active";
... but what is the proper way to remove the class from all other elements besides this one? ...但是从该元素之外的所有其他元素中删除该类的正确方法是什么?
Might be easier to organise list elements into an object and build them dynamically. 将列表元素组织成一个对象并动态构建它们可能会更容易。 Then add class as a property.
然后将class添加为属性。 So in your constructor:
因此,在您的构造函数中:
this.state = {
items: [
{id:"discovery", text:"Discovery"},
{id:"financial", text:"Financials"},
{id:"sales_stuff", text:"Sales"}
]
...
}
Then in your render 然后在您的渲染中
...
<ul>
{
this.state.items.map(item=>(
<li id={item.id} onClick={()=>this.activateGroup(item.id)} key={item.id}
className={this.state.activeGroup == item.id && "active"}>
{item.text}
</li>
))
}
</ul>
...
And then activate group can just be: 然后激活组可以是:
activateGroup(id) {
this.setState({activeGroup: id});
this.props.onNavChange(id);
}
This way you aren't manually adding/removing stuff from elements, and adding new items is easier (just add entry to state object). 这样,您就无需手动从元素中添加/删除内容,并且添加新项也更加容易(只需将条目添加到状态对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.