自定义React组件库使用时出现Cannot read properties of null (reading 'useRef')错误求助
自定义React组件库使用时出现
Cannot read properties of null (reading 'useRef')错误 问题详情
开发了一个包含多个React组件的自定义库,组件使用useCallback、useEffect、useMemo、useRef、useState等Hooks。将该库引入其他项目使用时,触发如下错误:
Cannot read properties of null (reading 'useRef') TypeError: Cannot read properties of null (reading 'useRef') at s.exports.f.useRef (http://localhost:3000/static/js/bundle.js:42272:16) at pn (http://localhost:3000/static/js/bundle.js:43986:13) at renderWithHooks (http://localhost:3000/static/js/bundle.js:20107:22) at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:23393:17) at beginWork (http://localhost:3000/static/js/bundle.js:24689:20) at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:9699:18) at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:9743:20) at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:9800:35) at beginWork$1 (http://localhost:3000/static/js/bundle.js:29674:11) at performUnitOfWork (http://localhost:3000/static/js/bundle.js:28921:16)
已确认库与宿主项目使用相同版本的React,尝试将部分devDependencies移至dependencies后问题仍存在,求排查方向。
解决方案
1. 配置peerDependencies
在库的package.json中,将react和react-dom声明为peerDependencies,而非dependencies或devDependencies。这能确保库复用宿主项目的React实例,避免重复加载导致Hook上下文失效:
"peerDependencies": { "react": "^18.0.0", "react-dom": "^18.0.0" }
2. 调整打包工具配置
使用Webpack或Rollup打包库时,需将React标记为外部依赖,不打包进库的bundle文件:
- Webpack:在
webpack.config.js中添加externals:externals: { react: 'react', 'react-dom': 'react-dom' } - Rollup:设置
external选项:export default { external: ['react', 'react-dom'], // 其他打包配置... }
3. 清理依赖缓存
删除库和宿主项目的node_modules文件夹、package-lock.json(或yarn.lock)文件,重新执行npm install或yarn install,排除缓存导致的版本冲突问题。
4. 检查组件导出规范
确保组件使用ES模块规范导出,避免CommonJS导出可能引发的Hook调用异常:
// 推荐的ES模块导出方式 export default MyCustomComponent; // 或 export { MyCustomComponent };
内容的提问来源于stack exchange,提问作者Pabrick
相关产品推荐
相关产品推荐

