gpt4 book ai didi

javascript - ReactJs。单击时组件不会隐藏

转载 作者:行者123 更新时间:2023-11-28 12:59:32 25 4
gpt4 key购买 nike

当我单击按钮时,会显示一个组件。如果再次单击该按钮,该组件不会更改状态。

    state = {
isActive: true
}
toggleMnu = () => {
this.setState({isActive: false});
}; // Show menu function

hideMnu = () => {
this.setState({isActive: true});
}; // Hide menu function

toggleOnClick = e => {
e.preventDefault();
!this.props.hideMnu
? this.toggleMnu()
: this.hideMnu();
};

render(){
return(
<button type="button" onClick={this.toggleOnClick}>Menu</button>
{this.state.isActive ? null : <div className="extended-menu-item">
{menuInfo.map((menuItem ,index)=>{return <ExtendedMenuItem click= {this.hideExtendedNav} {...menuItem} key={index}/>
})} // The component which shows menu on click
)}

最佳答案

这是因为你直接改变了状态。你应该这样做:

this.setState((prevState) => {
return {isActive: !prevState.isActive}
// reverse old state ^^
});

关于javascript - ReactJs。单击时组件不会隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com