react--todolist
作者:互联网
1 import React, { createRef, Fragment } from "react"; 2 3 export default class Todolist extends React.Component { 4 constructor() { 5 super(); 6 this.state = { 7 obj: [ 8 { title: "吃饭" }, 9 { title: "睡觉" }, 10 { title: "打豆豆" }, 11 { title: "学习" }, 12 { title: "打游戏" }, 13 ], 14 }; 15 this.inputval = createRef(); 16 } 17 fun = () => { 18 return this.state.obj.map((v, i) => { 19 return ( 20 <li key={i}> 21 <span>{v.title}</span>---- 22 <button onClick={this.del.bind(this, i)}>删除</button>----- 23 <button 24 onClick={() => { 25 this.updata(i); 26 }} 27 > 28 编辑 29 </button> 30 </li> 31 ); 32 }); 33 }; 34 add = () => { 35 if (this.inputval.current.value !== "") { 36 let newarr = []; 37 newarr = [...this.state.obj, { title: this.inputval.current.value }]; 38 this.setState({ 39 obj: newarr, 40 }); 41 this.inputval.current.value = ""; 42 } 43 }; 44 del = (i) => { 45 if (window.confirm("确认要删除吗?")) { 46 let newarr = []; 47 newarr = this.state.obj; 48 newarr.splice(i, 1); 49 this.setState({ 50 obj: newarr, 51 }); 52 } 53 }; 54 updata = (i) => { 55 let newword = window.prompt("请输入编辑后的内容"); 56 if (newword) { 57 let newarr = []; 58 newarr = this.state.obj; 59 newarr[i].title = newword; 60 this.setState({ 61 obj: newarr, 62 }); 63 } 64 }; 65 clear = () => { 66 this.setState({ 67 obj: [], 68 }); 69 }; 70 71 render() { 72 return ( 73 <Fragment> 74 {this.state.obj.length === 0 ? ( 75 <h3>暂无数据</h3> 76 ) : ( 77 <ul>{this.fun()}</ul> 78 )} 79 80 <input type="text" ref={this.inputval} /> 81 <button onClick={this.add}>添加</button> 82 <button onClick={this.clear}>清空</button> 83 </Fragment> 84 ); 85 } 86 }
标签:obj,title,--,newarr,inputval,react,todolist,state,let 来源: https://www.cnblogs.com/sprite692/p/16119602.html