
import React, { Component } from 'react'
import '../App.css'
export class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list: ['范文芳', '威风', '企鹅']
}
}
render() {
return (
<div>
<label htmlFor="list">添加列表项:</label>
<input
id="list"
className="input"
onChange={(e) => {this._onChangeInput(e)}}
value={this.state.inputValue}/>
<button onClick={() => {this._onClickButton()}}>添加</button>
<ul>
{
this.state.list.map((item, index) => {
return(
<li
onClick={() => {this._onClickLiDel(index)}}
key={index}>{item}</li>
)
})
}
</ul>
</div>
)
}
_onChangeInput(e) {
this.setState({
inputValue: e.target.value,
})
}
_onClickButton() {
const newList = [...this.state.list, this.state.inputValue]
if(this.state.inputValue !== '') {
this.setState({
list: newList,
inputValue: ''
})
}
}
_onClickLiDel(index) {
const newList = [...this.state.list]
newList.splice(index, 1)
this.setState({
list: newList
})
}
}
export default TodoList
组件拆分
TodoList.js
import React, { Component } from 'react'
import '../App.css'
import TodoItem from './TodoItem'
export class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list: ['范文芳', '威风', '企鹅']
}
}
render() {
return (
<div>
<label htmlFor="list">添加列表项:</label>
<input
id="list"
className="input"
onChange={(e) => {this._onChangeInput(e)}}
value={this.state.inputValue}/>
<button onClick={() => {this._onClickButton()}}>添加</button>
<ul>
{
this.state.list.map((item, index) => {
return(
<TodoItem
cont={item}
index={index}
key={index}
delItem={() => {this._onClickLiDel(index)}}/>
)
})
}
</ul>
</div>
)
}
_onChangeInput(e) {
this.setState({
inputValue: e.target.value,
})
}
_onClickButton() {
const newList = [...this.state.list, this.state.inputValue]
if(this.state.inputValue !== '') {
this.setState({
list: newList,
inputValue: ''
})
}
}
_onClickLiDel(index) {
const newList = [...this.state.list]
newList.splice(index, 1)
this.setState({
list: newList
})
}
}
export default TodoList
TodoItem.js
import React, { Component } from 'react'
export class TodoItem extends Component {
render() {
const { cont, } = this.props
return (
<div onClick={() => {this._onClickDiv()}}>{cont}</div>
)
}
_onClickDiv() {
this.props.delItem(this.props.index)
}
}
export default TodoItem
网友评论