You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TSX中如何在接口中声明HTMLButtonElement类型?

解决MUI Popover自定义组件的类型声明问题

直接把你的DialogProps接口里的any替换成对应的TypeScript类型即可,具体如下:

完整的类型修正后的接口

interface DialogProps {
  title?: string
  children: React.ReactNode
  isOpen: boolean
  setIsOpen(value: boolean): void
  anchorEl: HTMLButtonElement | null
  setAnchorEl: React.Dispatch<React.SetStateAction<HTMLButtonElement | null>>
}

类型说明

  • anchorEl:和官方示例保持一致,用HTMLButtonElement | null,因为锚点元素可能是一个按钮元素,也可能处于未设置的null状态。
  • setAnchorEl:这是React状态更新函数的标准类型,React.Dispatch<React.SetStateAction<T>>,其中T就是对应状态的类型(这里是HTMLButtonElement | null)。这个类型既支持直接传入新值,也支持传入函数式更新的回调。

扩展说明

如果你的Popover锚点元素不局限于按钮(比如可能是div、span等其他HTML元素),可以把类型改成更通用的HTMLElement | null,兼容性更广:

interface DialogProps {
  title?: string
  children: React.ReactNode
  isOpen: boolean
  setIsOpen(value: boolean): void
  anchorEl: HTMLElement | null
  setAnchorEl: React.Dispatch<React.SetStateAction<HTMLElement | null>>
}

内容的提问来源于stack exchange,提问作者Dereemii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:10:35