1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】TODOアプリ

Posted at

はじめに

 本記事は、プログラミング初学者が、学習を進めていて疑問に思った点について調べた結果を備忘録も兼ねてまとめたものです。
 そのため、記事の内容に誤りが含まれている可能性があります。ご容赦ください。
 間違いを見つけた方は、お手数ですが、ご指摘いただけますと幸いです。

ReactによるTODOアプリ

.jsx

class App extends Component {
  constructor() {
    super()
    this.state={
      count: 0,
      todoList: [],
      value: "",
    }
  }

  onChange(key_value) {
    this.setState(key_value)
  }

  add(todoElement) {
    this.setState({
      todoList: this.state.todoList.concat(todoElement),
      value: "",
    })
  }

  handleDelete(id) {
    let todoList = this.state.todoList.concat()
    let index = 0
    todoList.map((element, idx) => {
      if (element.id == id) {
        index = idx
      }
    })
    todoList.splice(index, 1)
    this.setState({todoList: todoList})
  }

  render() {
    const todoListNode = this.state.todoList.map(element => {
      return (
        <TodoElement
          key={element.id}
          element={element}
          onDelete={this.handleDelete.bind(this)}
          {...this.state}
        />
      )
    })
    return (
      <div>
        <h1>TODO App</h1>
        <AddTodo
          {...this.state}
          onChange={this.onChange.bind(this)}
          add={this.add.bind(this)}
        />
        <ul>
          {todoListNode}
        </ul>
      </div>
    );
  }
}

class AddTodo extends React.Component {
  onChange(e) {
    const key_value = {
      value: e.target.value,
    }
    this.props.onChange(key_value)
  }

  add() {
    if (this.props.value) {
      const todoElement = {
        content: this.props.value,
        id: this.props.todoList.length + 1,
      }
      this.props.add(todoElement)
    }
  }

  render() {
    return(
      <div>
        <input
          type="text"
          value={this.props.value}
          onChange={this.onChange.bind(this)}
        />
        <button onClick={this.add.bind(this)}>追加</button>
      </div>
    )
  }
}

class TodoElement extends React.Component {
  onDelete() {
    this.props.onDelete(this.props.element.id)
  }
  render() {
    return(
      <li>
        <span>{this.props.element.content}</span>
        <button onClick={this.onDelete.bind(this)}>削除</button>
      </li>
    )
  }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?