反应,从另一个函数访问componentDidMount中定义的变量

时间:2019-03-11 05:54:39

标签: javascript reactjs

我正在尝试在React中构建一个响应式下拉导航栏,并且遇到了障碍。我在componentDidMount

中定义了这些变量

componentDidMount = () => {
        let nav = document.getElementById("topNav")
        let main = document.getElementById("main")
        let menu = document.getElementsByClassName("menuitems")
        let close = document.getElementById("closeBtn")

    
        nav.style.height = "50px";
        main.style.marginTop = "50px";
        for (let i = 0; i < menu.length; i++) {
            menu[i].style.marginTop = "100px";
        };

        close.addEventListener("click", function () {
            const menuIcon = close.children;
            for (let i = 0; i < menuIcon.length; i++) {
                menuIcon[i].classList.toggle("active");
            }
        });
    }

并且我正在尝试在同一反应组件的onClick函数中访问它们

navToggle = () => {
  console.log(this.nav)
}

该变量记录为未定义。

所以,我的问题是,如何访问在compnentDidMount中定义的变量?

谢谢

1 个答案:

答案 0 :(得分:0)

componentDidMount范围内定义的变量将保留在该函数本身内。您需要将它们分配给类实例,例如

componentDidMount = () => {
    this.nav = document.getElementById("topNav")
    this.main = document.getElementById("main")
    this.menu = document.getElementsByClassName("menuitems")
    this.close = document.getElementById("closeBtn")


    this.nav.style.height = "50px";
    this.main.style.marginTop = "50px";
    for (let i = 0; i < menu.length; i++) {
        this.menu[i].style.marginTop = "100px";
    };

    this.close.addEventListener("click", function () {
        const menuIcon = this.close.children;
        for (let i = 0; i < menuIcon.length; i++) {
            menuIcon[i].classList.toggle("active");
        }
    });
}