TypeScript React Js,类型“void”不可分配给类型“((event:MouseEvent<HTMLDivElement, MouseEvent>) => void) | 不明确的'

gab*_*el 6 typescript reactjs

我有这个功能和这个类型:

类型 ClickHandler = (标签: Itag) => void;

类型 ShowHideDropItem = (标签: Itag) => void;

我的 tsx:

  const [menuItems, setMenuItems] = useState<ITag[]>(SideBarTags);

  const clickHandler: ClickHandler = (tag) => () => {
    showHideDropItem(tag);
  };

  const showHideDropItem: ShowHideDropItem = (tag) => {
    setMenuItems((items) =>
      items.map((item) => ({
        ...item,
        Active:
          item.Name === tag.Name ? (tag.Active === true ? false : true) : false,
      }))
    );
  };
Run Code Online (Sandbox Code Playgroud)

但我在 onClick 上收到此错误:

类型“void”不可分配给类型“((event: MouseEvent) => void) |” 不明确的'。TS2322

kin*_*ser 9

clickHandler柯里化函数(返回函数的函数)。考虑将其包含在您的类型中:

type ClickHandler = (tag: ITag) => (e: React.MouseEvent) => void;
Run Code Online (Sandbox Code Playgroud)

注意e: ( ) 参数的需要event取决于您是否想在函数中使用它。

编辑:你的函数看起来像:

const clickHandler: ClickHandler = (tag) => (e) => {
   e.preventDefault();
   showHideDropItem(tag);
};
Run Code Online (Sandbox Code Playgroud)

  • @gabriel 只要记住从 'react' 导入 `MouseEvent` 或简单地使用 `React.MouseEvent` 即可。然后,使用“e.preventDefault();”。 (2认同)