我正在尝试更新单击了哪个菜单项,因此相应地更改了类。我尝试过不同的方式来做这件事,但无法使其发挥作用。
继承我的代码:
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
menuState: [
{
menuName: 'homeMenuStatus',
homeMenuStatus: 'inactive',
ulSidenavClass: "nav child_menu no-display"
},
{
menuName: 'accountMenuStatus',
accountMenuStatus: 'active',
ulSidenavClass: "nav child_menu block-display"
},
{
menuName: 'contactMenuStatus',
peopleMenuStatus: 'inactive',
ulSidenavClass: "nav child_menu no-display"
},
]
}
}
handleClick(menuClicked) {
this.state.menuState.map((name, index) => {
let thisMenu = name.menuName;
if(name.menuName == menuClicked) {
if(this.state.menuClicked === 'active') {
this.setState({
...this.state,
menuClicked: 'inactive',
ulSidenavClass: 'block-display height-adjust'
});
} else {
this.setState({
...this.state,
menuClicked: 'active',
ulSidenavClass: 'block-display'
});
}
} else {
this.setState({
...this.state,
thisMenu: 'inactive',
ulSidenavClass: 'block-display height-adjust'
});
}
});
}
HTML:
<div>
<ul>
<li className={this.state.menuState[0].homeMenuStatus}>
<a onClick={() => this.handleClick('homeMenuStatus')}>Home </a>
<ul className={this.state.menuState[0].ulSidenavClass}>
<li>
<a href="#">Dashboard</a>
</li>
<li>
<a href="#">Activities</a>
</li>
</ul>
</li>
</ul>
</div>
我的状态对象没有改变。必须在setState()中做错事。任何人都可以指导我。
答案 0 :(得分:1)
您错误地更新了状态,使用prevState语法并返回映射的更新值,如
handleClick(menuClicked) {
this.setState((prevState) => ({menuState: prevState.menuState.map((name, index) => {
if(name.menuName === menuClicked) {
if(name.menuClicked === 'active') {
return {
...name,
menuClicked: 'inactive,
ulSidenavClass: 'block-display height-adjust'
}
} else {
return {
...name,
menuClicked: 'active,
ulSidenavClass: 'block-display'
}
}
} else {
return {
...name,
menuClicked: 'inactive,
ulSidenavClass: 'block-display height-adjust'
}
}
})}))
}
答案 1 :(得分:0)
您正在设置全局状态而不是特定对象的状态,有助于映射菜单设置它们并将新菜单添加到状态。
你正在设置this.state而不是你的this.state.desiredItem
随意提问,祝你好运:)
答案 2 :(得分:0)
你必须以另一种方式处理这个问题。以下handleClick
函数可以解决您的问题:
handleClick(menuClicked) {
let menuStateDup = this.state.menuState.slice();
let itemToUpdate = menuStateDup.find((element) => (
element.menuName === menuClicked
));
if ( itemToUpdate.menuClicked === 'active' ) {
itemToUpdate.menuClicked = 'inactive';
itemToUpdate.ulSidenavClass = 'block-display height-adjust';
} else {
// do vice-versa
}
this.setState({
menuState: menuStateDup
});
}