[英]remove class from all other elements when adding class
我有這個組成部分:
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>
);
}
}
這段代碼有效: event.target.className = "active";
...但是從該元素之外的所有其他元素中刪除該類的正確方法是什么?
將列表元素組織成一個對象並動態構建它們可能會更容易。 然后將class添加為屬性。 因此,在您的構造函數中:
this.state = {
items: [
{id:"discovery", text:"Discovery"},
{id:"financial", text:"Financials"},
{id:"sales_stuff", text:"Sales"}
]
...
}
然后在您的渲染中
...
<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>
...
然后激活組可以是:
activateGroup(id) {
this.setState({activeGroup: id});
this.props.onNavChange(id);
}
這樣,您就無需手動從元素中添加/刪除內容,並且添加新項也更加容易(只需將條目添加到狀態對象)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.