我是ReactJS的新手,正在尝试编辑待办事项列表,
我可以将输入添加到列表中,但是 本质上我想要的是当我单击编辑时我想要我的表单提交需要编辑特殊列表项的handleSubmit2,但是我想要编辑而不删除列表中的项,我想进行更改并在单击编辑时将其替换形式onSubmit = {this.handleSubmit2})。
我想在编辑时以及在编辑输入中编写过程中保留其ID,我想在“待办事项列表”上看到旧的列表项,但是在单击“编辑”后应将其替换为新的ID。
我整天都在努力,但是没有解决办法,希望有人能弄清楚,对不起我的英语,我说了长话:)
import React from "react";
import uuid from "uuid";
class Todolist extends React.Component {
state = { todolist: "", id: uuid(), edit: "", items: [], editclick: false };
handleChange = event => {
this.setState({ todolist: event.target.value });
};
handleSubmit = e => {
e.preventDefault();
const newstate = { id: this.state.id, todolist: this.state.todolist };
const updatedstate = [...this.state.items, newstate];
this.setState({
items: updatedstate,
id: uuid(),
todolist: "",
editclick: false
});
};
clearList = event => {
event.preventDefault();
this.setState({ items: [] });
};
handleDelete = id => {
this.setState({
items: this.state.items.filter(item => {
return item.id !== id;
})
});
};
handleEdit = id => {
const editing = this.state.items.filter(items => items.id !== id);
console.log(editing);
const editing2 = this.state.items.find(items => items.id === id);
console.log(editing2);
this.setState({ todolist: editing2.todolist, editclick: true, id: id });
};
handleSubmit2 = e => {
e.preventDefault();
const newstate = { id: this.state.id, todolist: this.state.todolist };
const editsubmit = this.state.items.filter(
items => items.id !== this.state.id || [...this.state.items, newstate]
);
console.log(editsubmit);
this.setState({ items: editsubmit, todolist: "", editclick: false });
};
render() {
return (
<div className="todoinput container">
<div className="row">
<div className="col-md-8 mx-auto text-center my-3 card card-body">
<form
onSubmit={
this.state.editclick ? this.handleSubmit2 : this.handleSubmit
}
>
<h2>Todo Input</h2>
<div className="input-group">
<div className="input-group-prepend">
<div className="input-group-text text-white bg-primary">
<i className="fas fa-book " />
</div>
</div>
<input
type="text"
onChange={this.handleChange}
value={this.state.todolist}
className="form-control"
placeholder="Add a Todo Item"
/>
</div>
<button
type="submit"
className={
this.state.editclick
? "btn btn-block bg-success mt-3"
: "btn btn-block bg-primary mt-3"
}
>
{this.state.editclick ? "Edit Item" : "Add Item"}{" "}
</button>
</form>
</div>
<div className="col-md-8 my-3 mx-auto card card-body">
<ul className="list-group my-4 ">
<h2 className="text-center">Todo List</h2>
{this.state.items.map(items => {
return (
<li
key={items.id}
className="list-group-item d-flex justify-content-between my-2"
>
{items.todolist}
<div>
<i
className="mx-2 fas fa-pen text-success"
onClick={() => this.handleEdit(items.id)}
/>
<i
className="mx-2 fas fa-trash text-danger"
onClick={() => this.handleDelete(items.id)}
/>
</div>{" "}
</li>
);
})}
</ul>
<button
className="btn btn-block bg-danger"
onClick={this.clearList}
>
Clear List
</button>
</div>
</div>{" "}
</div>
);
}
}
export default Todolist;