使用@Reactjs-popup在TypeScript中遭遇类型不兼容错误求助
解决@reactjs-popup在TypeScript中传入close回调的类型错误
问题
在TypeScript中使用@reactjs-popup组件时,传入接收close函数的子元素出现如下类型错误:
Type '(close: () => void) => ReactElement' is not assignable to type 'ReactNode'.
原始JavaScript代码:
<Popup modal overlayStyle={{ background: "rgba(255,255,255,0.98" }} contentStyle={contentStyle} closeOnDocumentClick={false} trigger={open => <BurgerIcon open={open} />} > {close => <Menu close={close} />} </Popup>
我的TypeScript代码:
<Popup modal overlayStyle={{ background: "rgba(255,255,255,0.98" }} contentStyle={contentStyle} closeOnDocumentClick trigger={(open: boolean): ReactElement => <BurgerIcon open={open} />} > {(close: () => void): ReactElement => <Menu close={close} />} </Popup>
解决办法
出现这个错误是因为@reactjs-popup的TypeScript类型定义中,默认将children标注为ReactNode,但开启modal模式时,组件实际支持传入一个接收close函数的渲染回调。
你可以尝试以下几种方案:
1. 类型断言绕开检查
直接将渲染回调断言为React.ReactNode,让TypeScript跳过类型校验:
<Popup modal overlayStyle={{ background: "rgba(255,255,255,0.98" }} contentStyle={contentStyle} closeOnDocumentClick trigger={(open: boolean): ReactElement => <BurgerIcon open={open} />} > {(close: () => void): ReactElement => <Menu close={close} />} as React.ReactNode </Popup>
2. 指定组件的模态Props类型
如果组件导出了专门的模态类型(比如ModalPopupProps),直接给Popup指定该类型:
import { Popup, ModalPopupProps } from '@reactjs-popup/core'; // ... <Popup<ModalPopupProps> modal overlayStyle={{ background: "rgba(255,255,255,0.98" }} contentStyle={contentStyle} closeOnDocumentClick trigger={(open: boolean): ReactElement => <BurgerIcon open={open} />} > {(close: () => void): ReactElement => <Menu close={close} />} </Popup>
3. 升级组件版本
若使用的是旧版@reactjs-popup,可能存在类型定义不完善的问题,直接升级到最新版本即可:
npm install @reactjs-popup/core@latest # 或使用yarn yarn add @reactjs-popup/core@latest
如果你的项目使用的是@reactjs-popup/reactjs-popup包,处理逻辑一致,优先通过升级版本修复类型问题。
内容的提问来源于stack exchange,提问作者A7med
相关产品推荐
相关产品推荐

