You need to enable JavaScript to run this app. 使用react-notifications-component时TypeScript报id不存在于{children?: ReactNode}类型怎么办
优惠活动
大模型
产品
解决方案
定价
更多

使用react-notifications-component时TypeScript报id不存在于{children?: ReactNode}类型怎么办

报错本质

该问题来源于react-notifications-component的旧版本TypeScript类型定义缺陷:content配置项的回调入参,被TS默认推导为仅包含children?: ReactNode的React通用属性类型,没有将通知实例的实际元数据(如通知ID)纳入类型范围,因此直接读取入参的id属性时会触发“属性不存在”的TS报错。
实际运行时,回调入参是完整的通知配置对象,只是类型定义未覆盖这些字段。

解决方法

方案一:闭包复用自定义通知ID(无类型依赖,优先使用)

调用store.addNotification时你已手动指定了通知ID,无需从content回调的入参中获取ID,直接通过作用域引用自定义的ID变量即可,完全绕开库的类型推导缺陷:

const notification = () => {
  // 单独定义通知ID,TS会自动推导其为string类型
  const targetId = 'myId';
  store.addNotification({
    id: targetId,
    content: () => (
      <Notifications
        handleCloseConfirm={() => store.removeNotification(targetId)}
      />
    ),
    width: 500,
    container: 'bottom-left',
    animationIn: ['animated', 'fadeIn'],
    animationOut: ['animated', 'fadeOut'],
    dismiss: {
      duration: 0,
      click: false,
      touch: false,
    },
  });
};

该方案不需要额外的类型断言,ID类型完全由业务代码管控,不会出现类型报错。

方案二:给回调入参补充明确类型

如果存在批量生成通知、需要动态读取回调中通知ID的场景,可以手动给content的回调入参标注类型,覆盖库自带的不完整类型推导:

store.addNotification({
  id: 'myId',
  content: (p: { id: string | number; [key: string]: any }) => (
    <Notifications
      handleCloseConfirm={() => store.removeNotification(p.id)}
    />
  ),
  // 其余配置保持不变
})
需同步修复的逻辑漏洞

现有子组件的关闭图标点击逻辑存在错误,会导致点击后无法触发关闭动作:
原代码片段:

<Icon iconName="notifications_close" onClick={() => handleSubmit} />

上述写法的箭头函数会直接返回handleSubmit的函数引用,并不会在点击时执行handleSubmit内部的关闭逻辑。需替换为以下任意一种正确写法:

  • 直接绑定函数引用:onClick={handleSubmit}
  • 在箭头函数内显式调用执行:onClick={() => handleSubmit()}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 13:36:07