首页 > 解决方案 > document.body.appendChild(form) 复制页面底部的表单

问题描述

我创建了一个表单来过滤表中的值。我将一个表单作为一个孩子附加到文档正文中,它正在复制表单。表格的第一行是:

<form id="form" onSubmit={ (e) => this.handleSubmit(e) } autoComplete="off">

handleSubmit 函数是:

handleSubmit = (e) => {
    event.preventDefault();
    // Running console.log(form) currently gives <form id="form" autoComplete="off">...</form>
    // When the following two lines are ran the form is duplicated at the bottom of the document body
    document.body.appendChild(form);
    this.props.onTriggerFilter(e);
    // Running console.log(form) now gives [form#form, form#form, form: form#form] 
    //This duplication stops me running the form again and adds another form at the bottom of the page
}

onTriggerFilter 函数是:

onTriggerFilter = () => {
    // Ignore the lines upto the return statement
    var tags = this.state.filterData.tags;

    if(this.state.filterData.tag)
        tags.push(this.state.filterData.tag)

    var filterData = this.state.filterData;
        filterData.tags = tags;
        filterData.tag = '';
    // This returns an array of objects which are displayed in a table
    return this.getAssets(filterData).then(assets => {
        this.setState({
            assets: assets,
            filterData: filterData
        })
    });
}

如何让表单停止复制?

标签: javascriptreactjs

解决方案


从字面上看,您的问题的答案已经存在于您的代码中:

// When the following two lines are ran the form is duplicated at the bottom of the document body
document.body.appendChild(form); // <--- this line adds "another" duplicate form to your HTML upon submitting it since it's in the handleSubmit function.

编辑是的,根据 MDN 的appendChild 文档,如果给出了参考,它应该简单地移动它而不是复制它。

在这种情况下,我的问题是,您从哪里获得form要附加的 var?问题中不存在该代码,我的猜测是您很可能没有附加引用,而是附加了一个独立元素,从而导致了重复。


推荐阅读