class ToDo extends React.Component {
constructor() {
super()
this.state = {
todos: [],
inputValue: null
}
this.changeValue = this.changeValue.bind(this)
this.addTodo = this.addTodo.bind(this)
this.removeTodo = this.removeTodo.bind(this)
}
changeValue(e) {
this.setState({inputValue: e.target.value})
}
addTodo(e) {
e.preventDefault()
const newTodoItem = {
id: Date.now(),
inputValue: this.state.inputValue
}
if(!this.state.inputValue.length) return
this.setState(state => ({
todos: state.todos.concat(newTodoItem),
inputValue: ''
}))
}
removeTodo(e) {
const et = e.target
const todos = this.state.todos
this.setState({
todos: todos.splice(todos.indexOf(et), 1)
})
}
render() {
return(
<div>
<form onSubmit={this.addTodo}>
<input
type='text'
name='todo'
placeholder='Enter a ToDo'
value={this.state.inputValue}
onChange={this.changeValue}
/>
<input type='submit' value='Add' />
<span>ToDos: {this.state.todos.length}</span>
</form>
<TodoList items={this.state.todos} itemClickEvent={this.removeTodo} />
</div>
)
}
}
class TodoList extends React.Component {
render() {
const items = this.props.items
return(
<ul>
{
items.map(item => (
<li key={item.id} onClick={this.props.itemClickEvent}>{item.inputValue}</li>
))
}
</ul>
)
}
}
ReactDOM.render(<ToDo />, document.querySelector('#app'))
In this todo list sample that I just imitated from the sample in the reactjs.org homepage, I added an event that removes the targeted todo item when clicked. The problem is, whichever of the todo items I click, instead of removing the target item itself, it removes all the items except the last item. Why such bug is happening?