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

自定义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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:53:17