最终效果:
React版的TodoList的实现:
首先搭建一个基本的react应用。
import React, { Component } from 'react';
import addItem from "../actions/action";
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
todoValue: ""
}
this.onInputChange = this.onInputChange.bind(this);
this.onBtnAddClick = this.onBtnAddClick.bind(this);
this.onBtnDeleteClick = this.onBtnDeleteClick.bind(this);
this.onItemClick = this.onItemClick.bind(this);
}
onInputChange(e) {
this.setState({
todoValue: e.target.value
})
}
onBtnAddClick() {
dispatch(addItem('Eat'))
}
onBtnDeleteClick() {
this.setState(() => {
const newTodos = [];
this.state.todos.map((item, key) => {
if (!item.completed) {
newTodos.push(item);
}
})
return {
todos: newTodos
}
})
}
onItemClick(index) {
this.setState(() => {
this.state.todos.map((item, key) => {
if (key === index) {
item.completed = !item.completed;
}
})
return {
todos: [...this.state.todos]
}
})
}
render(){
return (
<div>
<input
value={this.state.todoValue}
onChange={this.onInputChange}
placeholder="Please input something"
/>
<button
onClick={this.onBtnAddClick}
>
+
</button>
<button onClick={this.onBtnDeleteClick}>-</button>
<ul>
{
this.state.todos.map((item, index) => {
return (
<li
key={index}
style={{
textDecoration: item.completed ? 'line-through' : 'none'
}}
onClick={this.onItemClick.bind(this, index)}
>
{item.text}
</li>
)
})
}
</ul>
</div>
)
}
}
export default App