【React】react学习笔记07-综合应用todoList
todoList是react学习的一个祖传Demo,估计学过的都写过哈哈。这个demo比较简单,包含了三个组件,然后整合了之前学到的所有东西,只要能够
自己把这个demo写出来,那么基本上就可以做项目了。
博主上半年遇到个中后台项目,React框架,之前也从没见过React是个啥玩意,于是找了个视频看完了第一集,TodoList,比这个稍微多一个删除功能,
然后照着自己写了一个。之后就开始硬着头皮写项目了哈哈哈哈,现在已经有9个模块了,说实话我现在还不太敢直视当时写的东西,好在虽然代码写的丑,
但是很少有Bug哈哈。
直接上Demo了:
组件结构:
页面效果:
点击添加会将输入框中的内容添加到列表中:
代码:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> </head> <body> <!--react基础库--> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.js"></script> <!--bable转换库,ES语法以及Jax语法的转换--> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <div id="content"></div> <script type="text/babel"> //定义父组件 class Component extends React.Component{ //构造函数,在初始化组件的时候会执行 constructor(props){ super(props); this.state={ todoList: ['AAA','BBB','CCC'] } this.addTodoList=this.addTodoList.bind(this) } //render会进行页面的渲染,当state中数据更新或者发送ajax等事件被监听到都会触发render的刷新 render(){ return( <div> <h1>TODO LIST</h1> <Add addTodoList={this.addTodoList}/> <List todoList={this.state.todoList} /> </div> ); }; addTodoList(newTodoList){ const todoList = this.state.todoList; //todoList.unshift(newTodoList); this.setState({ todoList: [...todoList,newTodoList] }) } } //定义子组件 class Add extends React.Component{ constructor(props){ super(props); //固定写法指向this,最好使用箭头函数的方式 this.addTodoList=this.addTodoList.bind(this); } render(){ return( <div> <input type="test" ref={input =>this.newTodoListVal=input}/> <button onClick={this.addTodoList}>add</button> </div> ); } addTodoList(){ //获取input的值 const val = this.newTodoListVal.value; if(!val){ //空串布尔值为false return; } //调用传入的函数引用 this.props.addTodoList(val); this.newTodoListVal.value=''; } } //定义子组件 class List extends React.Component{ constructor(props){ super(props); } render(){ return( <ul> { //遍历数组 this.props.todoList.map((todo,index)=> {return <li key={index}>{todo}</li>}) } </ul> ); } } ReactDOM.render(<Component />,document.getElementById("content")); </script> </body> </html>