react版todolist

68 阅读1分钟

react脚手架生成命令

npx create-react -app 项目名称

相关插件安装

Code_4WU7B32SsK.png

项目结构

Code_x02mNNnu2e.png

todolist->index.js

import React, { Component } from 'react'
// import ListItem from "../ListItem"
export default class index extends Component {
    state = {
        inputValue:'',
        list:[]
    }
  render() {
    return (
      <div>
        <h2>TODO-LIST</h2>
        <input type="text" value={this.state.inputValue} onChange={this.bindChangeInputValue}/>
        <button type="button" onClick={this.onConfirm}>确定</button>
        {
          // map遍历
            this.state.list.map((item,index)=>{
              return(
                // 箭头函数,避免直接执行
                <p key={index} onClick={()=>{this.bindDelete(index)}}>{item}</p>
                // <ListItem item={item} />
                // 去掉上面的上面那行,取消注释下面那行,则没有删除功能
                // this.state.list.map((item,index)=><ListItem item={item} key={index} />)
              )
            })
        }
      </div>
    )
  }
  bindChangeInputValue=(e)=>{
    // 双向绑定
    // 先获取值
    let inputValue = e.target.value
    // 再更改状态 
    this.setState({inputValue})
  }
  onConfirm=()=>{
    // 点击确定拿值
    // 解构写法
    let {inputValue,list} = this.state
    // 把值压入list
    list.push(inputValue)
     // 更新list
    this.setState({list,inputValue:''}) // render重新执行
}
bindDelete = (index)=>{ 
  let {list} = this.state
  list.splice(index,1)
  this.setState({list})
}

}

ListItem->index.js

import React from 'react'
// rfc生成函数组件
/**
 * 如何设计组件
 * - 组件功能分析
 *     将todoList应用的列表项分离成组件ListItem
 * - 组件UI界面
 *     <p>{item}</p>
 * - 传入列表项参数
 * - 内部状态数据
 * 
 * @param {*} props 
 * @returns 
 */
export default function index(props) {
  return (
    <div>
        {props.item}
    </div>
  )
}

演示效果

todolist.gif