import React, { Component, Fragment } from "react";
class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list: []
}
}
render() {
return (
<Fragment>
<div>
<input value={this.state.inputValue} onChange={ (e) => this.handleInputChange(e) }/>
<button onClick={ this.handleBtnClick }>提交</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index} onClick={() => this.handleItemDelete(index)}>{item}</li>
)
})
}
</ul>
</Fragment>
);
}
handleInputChange = (e) => {
this.setState({
inputValue: e.target.value
})
}
handleBtnClick = () => {
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: ''
})
}
handleItemDelete = (index) => {
// immutable: state不允许做任何改变
// 直接修改this.state.xxx会影响后期性能优化
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list
})
}
}
export default TodoList;