繁体   English   中英

使用React.js显示消息时出错

[英]Getting error while displaying the message using React.js

我尝试仅在使用React.js提交表单后显示消息时遇到以下错误。

错误:

TypeError: Cannot read property 'insertAdjacentHTML' of undefined
TodoList.addItem
src/TodoList.js:30
  27 |       items:itemArray
  28 |     })
  29 |     this.inputElement.value='';
> 30 |     this.form.insertAdjacentHTML("beforebegin", '<p>Added successfully</p>');

这是我的代码:

addItem(e){
    e.preventDefault();
    if(this.state.editKey){
      this.saveEditedText();
      return;
    }
    var itemArray = this.state.items;
    if (this.inputElement.value !== '') {
      itemArray.unshift({
        text:this.inputElement.value,
        key:Date.now()
      })
      this.setState({
        items:itemArray
      })
      this.inputElement.value='';
      this.form.insertAdjacentHTML("beforebegin", '<p>Added successfully</p>');
    }
  }
<div className="wrapper">
<form onSubmit={this.addItem}>
<input ref={(a)=>this.inputElement=a} placeholder="enter task">
 </input>
<button type="submit">{this.state.editKey? "Update": "Add"}</button>
</form>
<TodoItems entries={this.state.items} delete={this.deleteItem} edit={this.editItem}/>
</div>

在这里,我需要显示成功消息,这意味着在表单提交后,此消息将在form元素之前准确显示。

问题出在这里, form onSubmit={this.addItem}>您尚未将ref分配给该形式

将其更改为<form ref={(el)=>this.form=el)} onSubmit={this.addItem}>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM