REACT中的状态(state)、列表渲染(map)、条件判断和标签解析(dangerouslySetInnerHTML)
import React, { Component,createRef } from 'react'
import ReactDOM from "react-dom";
export default class ToDoList extends Component {
constructor(){
super();
this.myref = createRef()
this.state = {
todoList:[11,22,33]
}
}
render() {
return (
<div>
<input ref={this.myref}></input>
<button onClick={()=> this.add()}>添加</button>
<ul>
{this.state.todoList.map((item,index) => {
return (
<li key={index} >
{}
<span dangerouslySetInnerHTML={{__html:item}}></span>{ }
<button onClick={()=>this.del(index)}>del</button>
</li>
)
})}
</ul>
{this.state.todoList.length === 0 && <div>暂无待办事项2</div>}
{this.state.todoList.length === 0?<div>暂无待办事项1</div>:null}
<div>{this.state.todoList.length === 0 && '暂无待办事项3'}</div>
</div>
)
}
add(){
let newList = [...this.state.todoList];
newList.push(this.myref.current.value);
this.setState({todoList:newList});
}
del(index){
let newList = this.state.todoList.slice();
newList.splice(index,1);
this.setState({todoList:newList});
}
}
ReactDOM.render(
<ToDoList></ToDoList>
,document.getElementById('root'))