diff --git a/src/App.jsx b/src/App.jsx index c869b09..98b2b97 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -3,11 +3,32 @@ import TodoList from './TodoList.jsx' import TodoAddForm from './TodoAddForm.jsx' class TodoApp extends React.Component { + + constructor(props) { + super(props); + } + + state = { + list: ['DefauleItem1','DefauleItem2'] + } + + removeElement = (idx) => { + //不想用setState所以用forceUpdate + this.state.list.splice(idx,1); + this.forceUpdate(); + } + + addElement = (text) => { + this.state.list.push(text); + this.forceUpdate(); + } + render() { return (

Todo App

- 123 + +
); } diff --git a/src/TodoAddForm.jsx b/src/TodoAddForm.jsx index fbf6003..5e3e886 100644 --- a/src/TodoAddForm.jsx +++ b/src/TodoAddForm.jsx @@ -1,15 +1,36 @@ import React from 'react' class TodoAddForm extends React.Component { + constructor(props) { + super(props); + } + state = { inputText: '' } - + + handleChange = (event) => { + this.setState({ ...this.state, inputText: event.target.value }) + } + + handleClick = (event) => { + // pass userinput to the parent component + this.props.addElement(this.state.inputText); + // clear userinput + this.setState({ ...this.state, inputText: "" }); + // focus on input + this.nameInput.focus(); + } + + componentDidMount() { + this.nameInput.focus(); + } + render() { return (
- - + { this.nameInput = input; }} type="text" value={this.state.inputText} onChange={this.handleChange} /> +
); } diff --git a/src/TodoItem.jsx b/src/TodoItem.jsx index 170af86..debad4d 100644 --- a/src/TodoItem.jsx +++ b/src/TodoItem.jsx @@ -1,10 +1,19 @@ import React from 'react' class TodoItem extends React.Component { + constructor(props){ + super(props) + } + + handleClick = (event) => { + this.props.removeElement(this.props.idx); + } + render() { return ( -
- +
+ + {this.props.text}
); } diff --git a/src/TodoList.jsx b/src/TodoList.jsx index d588dc4..1ee1b36 100644 --- a/src/TodoList.jsx +++ b/src/TodoList.jsx @@ -2,10 +2,20 @@ import React from 'react' import TodoItem from './TodoItem.jsx' class TodoList extends React.Component { + constructor(props){ + super(props); + } + render() { return ( -
- +
+ { + this.props.list.map( + (ele, index, array) => { + return (); + } + ) + }
); }