react学习-todolist-demo

最终效果如下:

代码结构如下 

react学习-todolist-demo_第1张图片

入口文件index.html如下



  
    
    
    
    
    React App
  
  
    
    

 index.js如下

import React from "react";
import ReactDOM from "react-dom";
import TodoList from "./TodoList";

ReactDOM.render(, document.getElementById("root"));

主要由两个组件组成,父组件TodoList和子组件TodoItem

父组件代码如下

import React, { Component, Fragment } from "react";
import TodoItem from "./TodoItem";
class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
      list: ["12", "23"]
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputSubmit = this.handleInputSubmit.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
    this.getItem = this.getItem.bind(this);
  }
  render() {
    return (
      
        {/* Fragment表示一个占位符*/}
        
    {this.getItem()}
); } getItem() { const list = this.state.list; return list.map((item, index) => { return ( ); }); } handleInputChange(e) { const value = e.target.value; this.setState(() => ({ inputValue: value })); } handleInputSubmit() { this.setState(prevState => ({ list: [...prevState.list, prevState.inputValue], inputValue: "" })); } handleItemDelete(index) { this.setState(prevState => { let list = [...prevState.list]; list.splice(index, 1); return { list }; }); } } export default TodoList;

子组件代码如下

import React, { Component } from "react";
class TodoItem extends Component {
    constructor(props){
        super(props);
        this.handleItemDelete = this.handleItemDelete.bind(this);
    }
  render() {
      const {content} = this.props;
    return (
{content}
) } handleItemDelete(){ const {handleDel,index}= this.props; handleDel(index) } } export default TodoItem

到这里就可以了,欢迎大神指点

你可能感兴趣的:(react学习-todolist-demo)