import React, { Component, Fragment } from "react";
import TodoItem from "./components/TodoItem";
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
list: []
};
}
render() {
return (
<Fragment>
<div>
<label htmlFor="insertLabel">输入内容:</label>
<input value={this.state.inputValue}
id="insertLabel"
ref={(input) => {this.input = input}}
onChange={this.handleChange.bind(this)}
/><button onClick={this.handleClick.bind(this)}>提交</button>
</div>
<ul>
{}
{
this.state.list.map((item, index) => {
return (
<TodoItem item={item} index={index} key={index} deleteItme={this.handleItemDelete.bind(this)} />
)
})
}
</ul>
</Fragment>
)
}
handleChange(e) {
console.log(e.target.value)
console.log(this)
this.setState({
inputValue: e.target.value,
})
console.log(this.state)
}
handleClick() {
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: ''
})
console.log(this.state)
}
handleItemDelete(index) {
console.log(index)
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list: list
})
}
}
export default TodoList;
import React, { Component, Fragment } from "react";
class TodoItem extends Component {
handleDeleteItem() {
this.props.deleteItme(this.props.index)
}
render() {
return (
<li onClick={this.handleDeleteItem.bind(this)}>{this.props.item}</li>
)
}
}
export default TodoItem;
import React, { useState, useEffect, useRef, Fragment } from "react";
import TodoItemFun from './components/TodoItemFun'
function TodoListFun() {
const [inputValue, setInputValue] = useState('')
const [list, setList] = useState([])
const initFormRef = useRef();
const handleInput = (e) => {
console.log(e.target.value)
setInputValue(e.target.value)
}
useEffect(() => {
initFormRef.current = list;
console.log(initFormRef.current)
}, [list]);
const handleClick = (e, value) => {
if (inputValue === '') {
return
}
setList([...list, inputValue])
}
const handleItemDelete = (index) => {
console.log(index);
const listValue = [...list]
listValue.splice(index, 1)
setList([...listValue])
}
return (
<Fragment>
<div>
<label htmlFor="insertLabel">请输入内容:</label>
<input value={inputValue} onChange={(e) => handleInput(e)} id="insertLabel" /><button onClick={(e) => handleClick(e, 'aa')}>提交</button>
<ul>
{
list.map((item, index) => {
return (<TodoItemFun key={index} item={item}
deleteItem={handleItemDelete}
index={index} /> )
})
}
</ul>
</div>
</Fragment>
);
}
export default TodoListFun;
import React, { useState, useEffect, useRef, Fragment } from "react";
function TodoItemFun(props) {
const handleDelteItem = () => {
props.deleteItem(props.index)
}
return (
<li onClick={() => handleDelteItem()}>
{props.item}
</li>
)
}
export default TodoItemFun;