父组件TodoList,子组件TodoItem
要实现的是todolist的列表展示和删除
展示部分交给组件TodoItem来做
上代码:
TodoList.js
import React from'react'
import TodoItem from './todoItem'
export default class TodoList extends React.Component{
constructor(props){
super(props)
this.state = {
inputValue: '',
list: []
}
}
handleInput = (event) => {
this.setState({
inputValue: event.target.value
})
}
handleAdd = () => {
const list = this.state.list
list.push(this.state.inputValue)
this.setState({
list
})
}
handleItemDel = (index) => {
const list = this.state.list
list.splice(index,1)
this.setState({
list
})
}
render(){
return <div>
<input onChange={this.handleInput}/>
<button onClick={this.handleAdd}>添加</button>
<ul>
{this.state.list.map((item,index)=>{
return <li>
<TodoItem
content={item}
index={index}
handleItemDel={this.handleItemDel} />
</li>
})}
</ul>
</div>
}
}
TodoItem.js
import React from 'react'
export default class TodoItem extends React.Component{
handleDel = () => {
this.props.handleItemDel(this.props.index)
}
render(){
return <div onClick={this.handleDel}>{this.props.content}</div>
}
}