我正在尝试创建一个触发菜单打开的按钮。我最初的想法是在按钮单击时设置状态,但实际情况是第一次单击对状态或类没有影响。第二次及后续点击时会触发更改。
我明白为什么可见性状态不起作用(因为 setState 是一个异步方法),但是如何让它从初始点击开始改变?
import React, { Component } from 'react';
export default class Social extends Component {
constructor() {
super();
// class of the div that will change
this.menuVisibility = "social--icons_cntr--close";
// managing the visibility of the menu items
this.state = {
visible: false
};
this.handleMouseDown = this.handleMouseDown.bind(this);
this.toggleMenu = this.toggleMenu.bind(this);
}
handleMouseDown(e) {
// if the state is visible, use the open class
if (this.state.visible === true) {
this.menuVisibility = "social--icons_cntr--open";
}
// if the state is not visible use the close class
else if (this.state.visible === false) {
this.menuVisibility = "social--icons_cntr--close";
}
// call the the toggleMenu method
this.toggleMenu();
e.stopPropagation();
}
toggleMenu() {
this.setState(
{ visible: !this.state.visible })
console.log("visibility: ", this.state.visible);
console.log("menuvis ", this.menuVisibility);
}
render() {
return(
<div className="social--cntr">
<div className={this.menuVisibility}>
<a className="social--icons-link" href="#">[X]</a>
</div>
<div className="social--btn-click social--btn-open"
onMouseDown={this.handleMouseDown}>
<span>+</span>
</div>
</div>
)
}
}
最佳答案
了解 setState
是异步,那么它的结构应该改变。根据状态将类绑定(bind)到条件语句,例如
<div className={{ (this.state.visible ? 'social--icons_cntr--open' : 'social--icons_cntr--close') }}>
然后在您的 onMouseDown
函数中只需使用 this.setState({{ !visible }})
。这样,组件将按照生命周期方法绑定(bind)到状态和更新,即在 ComponentDidUpdate
关于javascript - 立即更新 UI 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868370/