gpt4 book ai didi

javascript - 对待办事项列表使用react,如何让此删除按钮起作用?

转载 作者:行者123 更新时间:2023-12-01 02:43:06 25 4
gpt4 key购买 nike

我有一个简单的应用程序,除了能够从列表中删除项目之外,它运行良好。我已经将按钮添加到每个列表项中。我知道我想使用 .filter() 方法向状态传递一个没有删除的待办事项的新数组,但我不知道如何做这样的事情。

这是应用程序的主要组件:

class App extends Component {
constructor(props){
super(props);
this.state = {
todos: [
{ description: 'Walk the cat', isCompleted: true },
{ description: 'Throw the dishes away', isCompleted: false },
{ description: 'Buy new dishes', isCompleted: false }
],
newTodoDescription: ''
};
}

deleteTodo(e) {
this.setState({ })
}

handleChange(e) {
this.setState({ newTodoDescription: e.target.value })
}

handleSubmit(e) {
e.preventDefault();
if (!this.state.newTodoDescription) { return }
const newTodo = { description: this.state.newTodoDescription,
isCompleted: false };
this.setState({ todos: [...this.state.todos, newTodo],
newTodoDescription: '' });
}

toggleComplete(index) {
const todos = this.state.todos.slice();
const todo = todos[index];
todo.isCompleted = todo.isCompleted ? false : true;
this.setState({ todos: todos });
}

render() {
return (
<div className="App">
<ul>
{ this.state.todos.map( (todo, index) =>
<ToDo key={ index } description={ todo.description }
isCompleted={ todo.isCompleted } toggleComplete={ () =>
this.toggleComplete(index) } />
)}
</ul>
<form onSubmit={ (e) => this.handleSubmit(e) }>
<input type="text" value={ this.state.newTodoDescription }
onChange={ (e) => this.handleChange(e) } />
<input type="submit" />
</form>

</div>
);
}
}

然后这是待办事项的组件:

class ToDo extends Component {
render() {
return (
<li>
<input type="checkbox" checked={ this.props.isCompleted }
onChange={ this.props.toggleComplete } />
<button>Destroy!</button>
<span>{ this.props.description }</span>
</li>
);
}
}

最佳答案

Event handlers救援:

您可以将 onDelete 属性发送到每个 ToDo:

const Todo = ({ description, id, isCompleted, toggleComplete, onDelete }) => 
<li>
<input
type="checkbox"
checked={isCompleted}
onChange={toggleComplete}
/>
<button onClick={() => onDelete(id)}>Destroy!</button>
<span>{description}</span>
</li>

来自应用程序:

<ToDo 
// other props here
onDelete={this.deleteTodo}
/>

正如@Dakota 所指出的,在通过列表映射时使用索引作为键并不是一个好的模式。

也许只需更改您的 initialState 并为每个状态设置一个 id:

this.state = {
todos: [
{ id: 1, description: 'Walk the cat', isCompleted: true },
{ id: 2, description: 'Throw the dishes away', isCompleted: false },
{ id: 3, description: 'Buy new dishes', isCompleted: false }
],
newTodoDescription: '',
}

这也使从数组中删除项目变得更容易:

deleteTodo(id) {
this.setState((prevState) => ({
items: prevState.items.filter(item => item.id !== id),
}))
}

关于javascript - 对待办事项列表使用react,如何让此删除按钮起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47422915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com