gpt4 book ai didi

javascript - React JS 中的菜单切换

转载 作者:行者123 更新时间:2023-12-01 02:27:27 25 4
gpt4 key购买 nike

我正在react 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 &#8595;
<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 &#8595;
<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 &#8595;
<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 &#8595;
<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);

最佳答案

你忘记了一个if:

 else (ID == 4){
=>
else if (ID == 4){

关于javascript - React JS 中的菜单切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626385/

25 4 0