javascript - 立即更新 UI 的状态

标签 javascript reactjs

我正在尝试创建一个触发菜单打开的按钮。我最初的想法是在按钮单击时设置状态,但实际情况是第一次单击对状态或类没有影响。第二次及后续点击时会触发更改。

我明白为什么可见性状态不起作用(因为 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/

相关文章:

javascript - 如何使用 Jquery 检查图像来源的属性值?

javascript - 如何在 Mocha 中使用 console.log 语句测试功能?

javascript - react : Instantiate component once and use multiple times

reactjs - 在mapStateToProps之后接下来会调用什么

ReactJS Ant 设计选择组件模拟更改事件

javascript - 在 react-router 2 中禁用后退按钮

javascript - Vue 和 Jexcel 事件和计算字段

javascript - SetInterval定时改变单元格颜色

javascript - 如何在javascript中通过手机上的网络浏览器通过直播扫描条形码?

reactjs - RouterContext.push() 重新加载导航页面