如何修复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
相关产品推荐
相关产品推荐

