基于create-react-app做的小demo
比较简单直接上代码
效果图
import React from 'react' import Input from '../../components/Input/index' import List from '../../components/List/index' class Todo extends React.Component{ constructor(props){ super(props) this.state={ todos:[] }; this.submitFn=this.submitFn.bind(this);//注意看介绍了两种事件绑定 } submitFn(value){ console.log(value) const id=this.state.todos.length; this.setState({ todos:this.state.todos.concat({ id:id, text:value }) }) } deleteFn(id){ console.log(id) let data=this.state.todos; this.setState({ todos:data.filter(item=>{ if(item.id!==id){ return item } }) }) } render(){ return( <div style={{padding:'20px'}}> <Input submitFn={this.submitFn}/> <List todos={this.state.todos} deleteFn={this.deleteFn.bind(this)}/> </div> ) } } export default Todo;
import React from 'react' import "./input.css" //可以自定义外联样式 class Input extends React.Component{ constructor(props,context){ super(props,context); this.state={ value:'' }; this.changeHandler=this.changeHandler.bind(this); this.keyUpHandler=this.keyUpHandler.bind(this); } changeHandler(e){ // 实时同步数据 this.setState({value: e.target.value}) } keyUpHandler(e){ const value=this.state.value; console.log(e); if(e.keyCode===13&&value.trim()){ //提交并清空数据 this.props.submitFn(value); this.setState({ value:'' }) } } render(){ return( <div> <input type="text" className="inputStype" value={this.state.value} onChange={this.changeHandler} onKeyUp={this.keyUpHandler} /> </div> ) } } export default Input
import React from 'react' class List extends React.Component{ constructor(props){ super(props); this.state={ } } clickHandler(id){ this.props.deleteFn(id) } render(){ const data=this.props.todos; return( <ul style={{marginTop: '10px', fontSize: '20px', lineHeight: '30px'}}> {data.map((item,index)=>{ return <li key={index} onClick={this.clickHandler.bind(this,item.id)}> {item.text} </li> })} </ul> ) } } export default List