current position:Home>react demo1 TodoList

react demo1 TodoList

2022-05-15 02:05:07ALKEN ABBY

TodoList

Add and delete :

import React, {
    Component} from 'react';


class TodoList extends Component {
    


  // Usage method 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}*/}

                {
    /* If you want to support rich text recognition , More dangerous */}
                <span dangerouslySetInnerHTML={
    {
    __html: item}}></span>

                <button onClick={
    () => {
    
                  this.handleDel(index)
                }}>del
                </button>
              </li>)
            }
          </ul>


          {
    /*  Conditional rendering mode 1:*/}
          {
    /*{this.state.list.length === 0 ? <div> Nothing to do </div> : null}*/}

          {
    /* Conditional rendering mode 2:*/}
          {
    this.state.list.length === 0 && <div> Nothing to do </div>}

        </div>
    );

  }


  //  Process add 
  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 = '';
  }

  //  Process delete 
  handleDel = (index) => {
    
    // console.log('del', index)
    let newList = this.state.list.slice();
    newList.splice(index, 1);
    this.setState({
    
      list: newList,

    })
  }

}

export default TodoList;

copyright notice
author[ALKEN ABBY],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120527478762.html

Random recommended