mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-24 20:53:08 +00:00
We shouldn't be encouraging this pattern which requires good understanding of JS quirks and can lead to bugs in other instances.
67 lines
1.3 KiB
JavaScript
67 lines
1.3 KiB
JavaScript
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')
|
|
);
|