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

如何修复reactjs-popup示例代码中的TypeScript错误?

解决reactjs-popup的TypeScript类型错误

下面给你几个不用@ts-ignore的解决办法:

1. 给close函数指定正确类型

reactjs-popup的modal弹窗关闭函数的类型是() => void,明确给close参数加上这个类型,就能让TypeScript正确识别:

import React from 'react';
import Popup from 'reactjs-popup';

const MyPopup = () => (
  <div>
    <Popup
      trigger={<button>Information</button>}
      modal
    >
      {(close: () => void) => (
        <div>
          <div>What is this?</div>
          <button onClick={() => close()}>close</button>
        </div>
      )}
    </Popup>
  </div>
);

2. 升级reactjs-popup到最新版本

部分旧版本的reactjs-popup类型定义存在bug,没有正确处理modal模式下children为函数的场景,升级到最新版通常能自动修复这个类型推断问题。

3. 手动断言children的类型

如果前两种方法不生效,可以用类型断言告诉TypeScript这个函数是合法的ReactNode:

import React from 'react';
import Popup from 'reactjs-popup';

const MyPopup = () => (
  <div>
    <Popup
      trigger={<button>Information</button>}
      modal
    >
      {((close) => (
        <div>
          <div>What is this?</div>
          <button onClick={() => close()}>close</button>
        </div>
      )) as React.ReactNode}
    </Popup>
  </div>
);

4. 使用content属性替代children

换用Popup组件的content属性传递弹窗内容(该属性支持函数类型),也能避开这个类型报错:

import React from 'react';
import Popup from 'reactjs-popup';

const MyPopup = () => (
  <div>
    <Popup
      trigger={<button>Information</button>}
      modal
      content={(close) => (
        <div>
          <div>What is this?</div>
          <button onClick={() => close()}>close</button>
        </div>
      )}
    />
  </div>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:58:13