【REACT中的状态(state)、列表渲染(map)、条件判断和标签解析(dangerouslySetInnerHTML),例子:ToDoList】

REACT中的状态(state)、列表渲染(map)、条件判断和标签解析(dangerouslySetInnerHTML)

import React, { Component,createRef } from 'react'
import ReactDOM from "react-dom";
export default class ToDoList extends Component {
  constructor(){//构造器
  	  //子类必须调用super()
      super();//super 调用了父类(Component)的构造函数来去实例化子类本身,可以向父级传参
      //必须加this
      this.myref = createRef()

      this.state = {
      todoList:[11,22,33]
    }
  }
  //外部变量可以直接写
  // myref = createRef()

  // 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} >
                {/*dangerouslySetInnerHTML的作用相当于VUE中的v-html*/}
                <span dangerouslySetInnerHTML={{__html:item}}></span>{/*数据需要进行删除和添加的话,key最好是使用唯一辨识值id*/ }
                <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.concat();
    let newList = this.state.todoList.slice();
    newList.splice(index,1);
    this.setState({todoList:newList});
  }
}

ReactDOM.render(
  // <React.StrictMode>
    <ToDoList></ToDoList>
  // <ToDoList/>
  // </React.StrictMode>
  ,document.getElementById('root'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值