首页 > 解决方案 > this.removeNum 不是 HTMLButtonElement.onclick 的函数

问题描述

我已经研究了所有可能类似的案例并应用了他们的解决方案,但仍然无济于事。每次单击 X 图标时,我都会收到 this.removeNum 的非函数错误。有趣的是,每次我点击加号图标时,addNum 函数都运行良好,此处未显示;唯一的区别是我正在使用 DOM 为 removeNum 创建 onClick 属性。以下是我的代码:

constructor(props) {
    super(props);
    this.state = {
        phoneCnt: 1
    };
    this.addNum = this.addNum.bind(this);
    this.removeNum = this.removeNum.bind(this);
}

removeNum() {
    console.log("test");
    console.log(this.state.phoneCnt);
    this.state.phoneCnt--;
    this.id.remove();
}

addNum() {
    // let divRemWrap = document.createElement("div");

    let divWrap = document.createElement("div");
    divWrap.classList.add("input--spacing");
    divWrap.setAttribute("id", `phone${this.state.phoneCnt}`);
    this.state.phoneCnt++;

    let numSpan = document.createElement("label");
    numSpan.classList.add("hover--highlight");
    let inputNum = document.createElement("input");
    inputNum.classList.add("input--borders");
    inputNum.setAttribute("type", "text");
    inputNum.setAttribute("name", "telephone number");
    inputNum.setAttribute("maxlength", "11");
    inputNum.setAttribute("size", "11");
    let penIcon = document.createElement("i");
    penIcon.classList.add("fas", "fa-pencil-alt", "icon--space__schoolHeaderLeftForm", "icon-pencil-p--size__schoolHeaderLeftForm");
    numSpan.appendChild(inputNum);
    numSpan.appendChild(penIcon);

    let remBtn = document.createElement("button");
    remBtn.setAttribute("type", "button");
    remBtn.classList.add("btn-noStyle");
    remBtn.setAttribute("onClick", "this.removeNum()");
    let timesIcon = document.createElement("i");
    timesIcon.classList.add("fas", "fa-times", "icon-pencil-p--size__schoolHeaderLeftForm", "icon--space__schoolHeaderLeftForm")
    remBtn.appendChild(timesIcon);

    divWrap.appendChild(numSpan);
    divWrap.appendChild(remBtn);

    document.getElementById("addNum").appendChild(divWrap);
}

以下链接是我的错误https://gyazo.com/c8689d5fcf76a79d2924f9454ea18e62的简短 gif 。

标签: htmlreactjsjsx

解决方案


推荐阅读