React+TypeScript中ReactNotifications组件报TS2604错误求助
React + TypeScript中使用react-notifications-component报TS2604错误
问题描述
我正在使用React结合TypeScript开发项目,编写了如下代码:
import { Provider } from 'react-redux' import initStore from './store' import TestApp from './TestApp' import ReactNotifications from 'react-notifications-component' const store = initStore() function App() { return ( <Provider store={store}> <ReactNotifications /> <TestApp /> </Provider> ); } export default App
按照react-notifications-component的文档说明,这段代码应正常运行,但ReactNotifications组件却报出错误:
JSX element type 'ReactNotifications' does not have any construct or call signatures.ts(2604)
我已安装@types/react-notifications-component,错误仍存在。请问我忽略了什么?
解决方法
这个错误的核心原因是导入方式不符合库的类型定义规范,react-notifications-component的ReactNotifications组件是作为命名导出存在的,而非默认导出。
修正步骤:
- 将默认导入改为命名导入,同时别忘了引入组件样式(否则通知会无样式效果):
import { Provider } from 'react-redux' import initStore from './store' import TestApp from './TestApp' // 改为命名导入 import { ReactNotifications } from 'react-notifications-component' // 引入组件样式文件 import 'react-notifications-component/dist/theme.css' const store = initStore() function App() { return ( <Provider store={store}> <ReactNotifications /> <TestApp /> </Provider> ); } export default App
- 若你坚持使用默认导入,也可以通过访问默认导出的属性来使用组件,但这种方式易造成混淆,不推荐:
import ReactNotifications from 'react-notifications-component' // 使用组件时 <ReactNotifications.ReactNotifications />
补充说明
@types/react-notifications-component的类型定义中,默认导出是一个包含组件的对象,而非组件本身。直接将默认导入的结果作为JSX组件使用时,TypeScript会判定它不具备组件的构造/调用签名,从而抛出TS2604错误。
内容的提问来源于stack exchange,提问作者xyz83242
相关产品推荐
相关产品推荐

