我正在实施一个菜单切换反应js。问题是当我点击一个li项目时。无论如何,最后一个li项目总是打开。我只希望显示特定的菜单。其他菜单应该隐藏。我找不到问题。
代码笔链接: https://codepen.io/nahidmbstu/pen/QQNdjN
代码在这里
var el = document.querySelector("#app")
class Editor extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = { display : false,
display1 : false ,
display2 : false,
display3 : false, };
}
handleChange(e) {
var ID = e.target.id
console.log(ID )
if (ID == 1 )
{
this.setState({ display: ! this.state.display } );
}
else if (ID == 2)
{
this.setState({ display1: ! this.state.display1 } );
}
else if (ID == 3)
{
this.setState({ display2: ! this.state.display2 } );
}
else (ID == 4)
{
this.setState({ display3: ! this.state.display3 } );
}
}
render() {
return (
<div className="container">
<div className= "row">
<div className= "col-md-12 offset-3">
Header
</div>
</div>
<div className= "row">
<div className= "col-md-4 offset-3">
<ul class = "menu-list">
<li class = "primary-menu" id = "1" onClick = { this.handleChange }>fastfood ↓
<ul class = "submenu-list">
<li class = "submenu" style={ { display: this.state.display ? 'block' : 'none' }}>Berger</li>
<li class = "submenu" style={ { display: this.state.display ? 'block' : 'none' }}>Pizza</li>
</ul>
</li>
<li class = "primary-menu">Coffee</li>
<li class = "primary-menu" id = "2" onClick = { this.handleChange }>Tea ↓
<ul class = "submenu-list" >
<li class = "submenu" style={ { display: this.state.display1 ? 'block' : 'none' }}>Black tea</li>
<li class = "submenu" style={ { display: this.state.display1 ? 'block' : 'none' }}>Green tea</li>
</ul>
</li>
<li class = "primary-menu" id = "3" onClick = { this.handleChange }>Milk ↓
<ul class = "submenu-list">
<li class = "submenu" style={ { display: this.state.display2 ? 'block' : 'none' }}>cow milk</li>
<li class = "submenu" style={ { display: this.state.display2 ? 'block' : 'none' }}>goat milk</li>
</ul>
</li>
<li class = "primary-menu" id = "4" onClick = { this.handleChange }>Cold Drinks ↓
<ul class = "submenu-list">
<li class = "submenu" style={ { display: this.state.display3 ? 'block' : 'none' }}>Coke</li>
<li class = "submenu" style={ { display: this.state.display3 ? 'block' : 'none' }}>Sprite</li>
</ul>
</li>
</ul>
</div>
<div className= "col-md-8 offset-3">
</div>
</div>
</div>
);
}
}
ReactDOM.render(<Editor />, el);
答案 0 :(得分:0)
你忘记了一个if:
else (ID == 4){
=>
else if (ID == 4){
答案 1 :(得分:0)
你的最后一个if子句无法正常工作。
https://codepen.io/anon/pen/gvMwXL
更新了您的codepen
//....
else if (ID == 4) //add "if" here
{
this.setState({ display3: ! this.state.display3 } );
}
//....