如何在 React 中将删除垃圾桶图标添加到 bootstrap table 行?

How to add delete trash icon to bootstrap table rows in React?

我有一个带有一些字段的 table,我想在每一行上放置一个垃圾桶图标,然后在单击它时删除该行。我在该行显示该图标并将相应行的 customerId 字段发送到删除函数时遇到问题。

我从 bootstrap site 复制了垃圾桶图标 这是代码:

import React, { useEffect, useState } from 'react';

import * as ReactBootStrap from 'react-bootstrap';
import * as service from '../service/FetchCustomerService';
import Button from 'react-bootstrap/Button'

function MainPanel() {

  const [customers, setCustomers] = useState([]);
  

  useEffect(() => {
    const fetchPostList = async () => {
      const response = await service.getCustomerList();
      setCustomers(response.data);
      console.log(response.data)
    };
    fetchPostList()
  }, []);



  const deleteCustomer = (customerId) => {
    // CALL DELETE FUNCTION WITH CUSTOMERID
    console.log(customerId);
  }

  return (
    <ReactBootStrap.Table striped bordered hover>
        <thead>
          <tr>
            <th>ID</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {customers &&
            customers.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.firstName}</td>
                <td>{item.lastName}</td>
//problem is the following line
                    <td><Button onClick={this.deleteCustomer(this.customerId)} className='bi-trash'>Delete</Button></td>
                  </tr>
                ))}
            </tbody>
          </ReactBootStrap.Table>
      );
    }
    
    export default MainPanel;

但是有了这个,只有按钮没有图标,我无法将 customerId 传递给函数,错误是:

MainPanel.js:45 Uncaught TypeError: Cannot read properties of undefined (reading 'deleteCustomer')

我该如何解决?

您不想使用 this.deleteCustomer,因为您正在使用功能组件。

您想使用

<Button onClick={() => deleteCustomer(customerId)}></Button>

如果你只是传递 deleteCustomer(customerId) 它可能会在加载时触发函数。如果您像上面那样传递回调,它应该会按预期工作。

它不起作用,因为 font-awesome 库要求您制作带有 i 标签的图标。您正在将 classname 应用到一个不起作用的按钮元素。下面是它应该是什么。

例如:

<i class="bi-trash"></i>

页面上有了图标后,您可以用按钮包裹 i 标签:

<Button onClick={this.deleteCustomer(this.customerId)}>
     <i class="bi-trash"></i>
</Button>

上面的这个例子可以工作,但是因为你使用的是 React,所以你应该使用 FontAwesomeIcon 组件。 (如果您还没有安装 font awesome 作为依赖项。Link 到此处的文档:https://fontawesome.com/docs

对于这个特定的图标,链接在这里:https://fontawesome.com/icons/trash?s=solid

进口:

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrash } from "@fortawesome/free-solid-svg-icons";

完整按钮:

<Button onClick={this.deleteCustomer(this.customerId)}>
    <FontAwesomeIcon icon={faTrash} />
</Button>

现在说说为什么它说它不能读取这个未定义的 属性。你需要删除这个。在函数引用的开头,这是针对基于 class 的组件的,这是功能性的。因此,通过此更正:

<Button onClick={() => deleteCustomer(this.customerId)}>
    <FontAwesomeIcon icon={faTrash} />
</Button>

() => 开头的原因是,如果你不包含它,React 会将其视为 onload,并且 运行 它会在组件加载时执行一次。