状态组件 => 组件拆分
import React, { Component, Fragment } from 'react'
import TodoItem from './TodoItem';
class TodoList extends Component {
constructor() {
super()
this.state = {
list: [],
inputValue: ''
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
this.handleDelete = this.handleDelete.bind(this)
}
handleBtnClick() {
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: ''
})
}
handleInputChange(e) {
this.setState({
inputValue: e.target.value
})
}
handleDelete(index) {
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list: list
})
}
getTodoItems() {
const { list } = this.state;
return (
list.map((item, index) => {
return (
<TodoItem
key={index}
index={index}
content={item}
delete={this.handleDelete}
/>
)
})
)
}
render() {
const { inputValue } = this.state;
return (
<Fragment>
<div>
<input value={inputValue} onChange={this.handleInputChange}/>
<button onClick={this.handleBtnClick}>add</button>
</div>
<ul>{this.getTodoItems()}</ul>
</Fragment>
)
}
}
export default TodoList
import React from 'react';
class TodoItem extends React.Component {
constructor() {
super()
this.handleDelete = this.handleDelete.bind(this)
}
handleDelete() {
this.props.delete(this.props.index)
}
render() {
return (
<li onClick={this.handleDelete}>{this.props.content}</li>
)
}
}
export default TodoItem
网友评论