实现增加和删除:
import React, {Component} from 'react';
class TodoList extends Component {
//使用方法2:
myRef = React.createRef();
state = {
list: [1, 2, 3]
}
render() {
return (
<div>
<input type="text" ref={this.myRef}/>
<button onClick={() => {
this.handleAdd();
}}>add
</button>
<ul>
{
this.state.list.map((item, index) => <li key={item}>
{/*{item}*/}
{/*如果要支持富文本识别的话,比较危险*/}
<span dangerouslySetInnerHTML={{__html: item}}></span>
<button onClick={() => {
this.handleDel(index)
}}>del
</button>
</li>)
}
</ul>
{/* 条件渲染方式1:*/}
{/*{this.state.list.length === 0 ? 暂无待办事项 : null}*/}
{/*条件渲染方式2:*/}
{this.state.list.length === 0 && <div>暂无待办事项</div>}
</div>
);
}
// 处理添加
handleAdd = () => {
console.log('click1', this.myRef.current.value)
let newList = [...this.state.list];
newList.push(this.myRef.current.value);
this.setState({
list: newList
})
this.myRef.current.value = '';
}
// 处理删除
handleDel = (index) => {
// console.log('del', index)
let newList = this.state.list.slice();
newList.splice(index, 1);
this.setState({
list: newList,
})
}
}
export default TodoList;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)