我在React有一个todolist,我可以删除todo-s但是我想对已完成的todos应用删除。之后,将它们列为已完成将会很棒。这怎么可能?我应该在代码中更改什么?我试图在数组中使用对象,但这会导致diff,erros。
import React, { Component } from 'react';
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
items: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleChange(event) {
this.setState({items: event.target.value})
console.log(event.target.value);
}
handleSubmit(event) {
this.setState({
list: [...this.state.list, this.state.items],
items: ''
})
event.preventDefault();
}
handleRemove(index) {
const filteredArray = this.state.list.filter((_, i) => i !== index); // used underscore as a convention to address nothing is going there
this.setState({
list: filteredArray
});
}
render() {
return (
<div className='header main'>
<form onSubmit={this.handleSubmit} >
<label>
<input className='new-todo'
placeholder='What needs to be done?'
type="text"
value={this.state.items}
onChange={this.handleChange} />
</label>
</form>
<ul className='todo-list'>
{this.state.list.map((item, index) => (
<li className='list-view' key={index+1}>{item}<button className='list-view-button' onClick={this.handleRemove.bind(this, index) }>X</button></li>
))}
</ul>
<div className='footer'>
Remaining: {this.state.list.length}
</div>
</div>
);
}
}
export default ToDoList;
答案 0 :(得分:1)
目前你只有一个代表待办事项的字符串数组。
我会为你的物品状态执行此操作:
items: [
{
desc: "todo content",
status: "new"
},
{
desc: "todo content",
status: "completed"
},
{
desc: "todo content",
status: "archived"
}
];
现在当您循环浏览todos时,您可以检查不同设计显示的状态。
或者您可以根据特定状态过滤待办事项, 即:
this.state.items.filter(item => item.status==="new")
这只会给你“新”的待办事项。