學完前面的生命週期,事件後就能自己寫一個todo List ,也就是新增列表
官網範例寫的
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<label htmlFor="new-todo">
What needs to be done?
</label>
<input
id="new-todo"
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (this.state.text.length === 0) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(state => ({
items: state.items.concat(newItem),
text: ''
}));
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('todos-example')
);
將他用hook再寫一次,稍微改一下
import React, { useState } from 'react'
import './app4.scss';
const Todo = ({ todo }) => <li key={todo.id}>{todo.text}</li>;
function TodoForm({ addTodo }) {
const [value, setValue] = useState("");
const [gonum, goClick] = useState(0);
const handleSubmit =(e)=> {
e.preventDefault();
addTodo(value);
setValue("");
goClick(gonum + 1)
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
className="input"
value={value}
onChange={e => setValue(e.target.value)}
/>
<button>
Add #{gonum}
</button>
</form>
);
}
export default function App3() {
const [todos, setTodos] = useState([]);
const addTodo = text => {
const newTodos = [...todos, { text }];
setTodos(newTodos);
};
return (
<div className="app">
<div className="todo-list">
<TodoForm addTodo={addTodo} />
</div>
<ul>
{todos.map((todo, index) => (
<Todo key={index} index={index} todo={todo}/>
))}
</ul>
</div>
)
}
運用組件props傳值,來模仿官網的範例。