{value}" ; 2. Use the list click event "handleItemClick(index) {...}" to implement the deletion function."/> {value}" ; 2. Use the list click event "handleItemClick(index) {...}" to implement the deletion function.">

Home >Web Front-end >Front-end Q&A >How to implement the delete function in react

How to implement the delete function in react

藏色散人
藏色散人Original
2023-01-06 16:17:082855browse

React method to implement the delete function: 1. Add a click event to the li tag, with code such as "5b49c58954d535c97d5c026b7aed46f2 {value}bed06894275b65c1ab86501b08a632eb"; 2. Use the list click event "handleItemClick(index) {...}" to implement the deletion function.

How to implement the delete function in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to implement the delete function in react?

React implements the TodoList deletion function

To realize clicking on an item in the list, delete the item

1. Add a click event to the li tag :handleItemClick

<li key= {index} onClick={this.handleItemClick.bind(this, index)}>{value}</li>

2. Click event function:

// 列表点击事件
   handleItemClick(index) {
       const list = [...this.state.list];
       list.splice(index, 1);
       this.setState({
           list: list
       })
   }

The complete code is as follows:

import React, {Component, Fragment} from 'react';
class TodoList extends Component {
   constructor(props) {
       super(props);
       this.state = {
           inputValue: '',
           list: []
       }
   }
   handleInputChange(e) {
       this.setState({
           inputValue: e.target.value
       })
   }
   // 松开键盘会触发该事件
   handleKeyUp(e) {
       // 判断是不是点的回车键
       if (e.keyCode === 13) {
           const list = [...this.state.list, this.state.inputValue];
           this.setState({
               list: list,
               inputValue: ''
           })
       }
   }
   // 列表点击事件
   handleItemClick(index) {
       const list = [...this.state.list];
       list.splice(index, 1);
       this.setState({
           list: list
       })
   }
   render() {
       return(
           
           
           
    { this.state.list.map((value,index) => { return ( <li key= {index} onClick={this.handleItemClick.bind(this, index)}>{value}</li> ) }) }
) } } export default TodoList;

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement the delete function in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn