【发布时间】:2020-06-23 17:37:29
【问题描述】:
我是 react 初学者,我有 3 个问题 1)如何防止创建空白任务(见附图)
2)如何为 UI 的已检查任务添加删除线?
3)为什么会出现这个错误
警告:列表中的每个孩子都应该有一个唯一的“key”属性。
我的反应代码:
import React from "react";
import "./styles.css";
let id = 0
const Todo = props => (
<li>
<input type="checkbox" checked={props.todo.checked} onChange={props.onToggle} />
<button onClick={props.onDelete}>delete</button>
<span>{props.todo.text}</span>
</li>
)
class App extends React.Component {
constructor() {
super()
this.state = {
todos: [],
}
}
addTodo() {
const text = prompt("TODO text please!")
this.setState({
todos: [
...this.state.todos,
{id: id++, text: text, checked: false},
],
})
}
removeTodo(id) {
this.setState({
todos: this.state.todos.filter(todo => todo.id !== id)
})
}
toggleTodo(id) {
this.setState({
todos: this.state.todos.map(todo => {
if (todo.id !== id) return todo
return {
id: todo.id,
text: todo.text,
checked: !todo.checked,
}
})
})
}
render() {
return (
<div>
<div>Todo count: {this.state.todos.length}</div>
<div>Unchecked todo count: {this.state.todos.filter(todo => !todo.checked).length}</div>
<button onClick={() => this.addTodo()}>Add TODO</button>
<ul>
{this.state.todos.map(todo => (
<Todo
onToggle={() => this.toggleTodo(todo.id)}
onDelete={() => this.removeTodo(todo.id)}
todo={todo}
/>
))}
</ul>
</div>
)
}
}
export default App;
【问题讨论】:
-
欢迎来到 SO!我肯定会鼓励使用谷歌搜索错误(甚至在 SO 上搜索),因为
Warning: Each child in a list should have a unique "key" prop.是人们在渲染集合时在 React 中遇到的一个非常常见的错误。这个答案stackoverflow.com/questions/28329382/… 详细介绍了key道具。
标签: javascript html reactjs react-dom