首页 > 解决方案 > 打字稿错误 2769 - 尝试将流程信息传递给数据状态以在模式上使用它

问题描述

我正在尝试将进程从 .map 函数传递到 setData 状态,以便我可以在模式上显示它,并给出以下错误:

“没有重载匹配此调用。重载 1 of 2, '(props: { component: ElementType; } & { children?: ReactNode; classes?: Partial | undefined; color?: "inherit" | ... 8 更多 .. . | undefined; ... 5 more ...; viewBox?: string | undefined; } & CommonProps & Omit<...>): Element',出现以下错误。在类型 '{ 中缺少属性 'component' onClick: void; }' 但在类型 '{ component: ElementType; }' 中是必需的。重载 2 of 2, '(props: DefaultComponentProps<SvgIconTypeMap<{}, "svg">>): Element',给出以下错误。类型 'void' 不可分配给类型 'MouseEventHandler | undefined'。TS2769"

代码如下:

import { Box, Modal } from "@mui/material";
import React, { FC, Fragment, useState } from "react";
import LaunchIcon from "@mui/icons-material/Launch";
interface Props {
  setProcesses: (val: any) => void;
  processes: Array<any>;
}
const CourseTable: FC<Props> = ({ processes, setProcesses }) => {
  const [open, setOpen] = useState<boolean>(false);
  const [data, setData] = useState<any>();

  const handleOpen = (process: any) => {
    setData(process);
    setOpen(true);
    console.log(data);
  };

  const handleClose = () => setOpen(false);

  const diferenceDates = (value: any) => {
    const dateNow = new Date();
    const dateCreation = new Date(`${value}`);
    const diffTime = Math.abs(dateNow.valueOf() - dateCreation.valueOf());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const dateVisitTrimmed = (value: any) => {
    const visitDate = new Date(value);
    const dateVisit = visitDate.toLocaleDateString();
    return dateVisit;
  };

  return (
    <div className='coursetable'>
      <table>
        <thead>
          <tr>
            <th>N/Ref</th>
            <th>V/Ref</th>
            <th>Proponente</th>
            <th>Contacto</th>
            <th>Morada</th>
            <th>Visita</th>
            <th>Dias em Curso</th>
          </tr>
        </thead>
        <tbody>
          {processes.map((process: any) => (
            <tr>
              <td>{process.processNumber}</td>
              <td>{process.vRef}</td>
              <td>{process.clientName}</td>
              <td>{process.clientContact}</td>
              <td>{process.address}</td>
              <td>{dateVisitTrimmed(process.visitDate)}</td>
              <td>{diferenceDates(process.creationDate)}</td>
              <td>
                <LaunchIcon onClick={handleOpen(process)} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <Modal open={open} onClose={handleClose}>
        <Box>cenas da vida</Box>
      </Modal>
    </div>
  );
};

export default CourseTable;

标签: javascriptreactjstypescript

解决方案


该行:

<LaunchIcon onClick={handleOpen(process)} />

是问题。组件的onClickprop 应该是function,但你给它的却是 的结果handleOpen,而不是handleOpen函数本身。

要解决此问题,请将您的点击处理程序包装到一个匿名函数中,该函数可以process通过其闭包提供正确的:

<LaunchIcon onClick={() => handleOpen(process)} />

推荐阅读