在尝试仅在使用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>
这里我需要在表单提交后显示成功消息表示此消息将在表单元素之前完成。
答案 0 :(得分:0)
问题在于form onSubmit={this.addItem}>
您尚未为表格
将其更改为<form ref={(el)=>this.form=el)} onSubmit={this.addItem}>