React项目Bootstrap组件无法渲染报错,已解决(安装目录错误)
React集成Bootstrap组件无法渲染问题排查与解决
问题现象
创建React项目并集成React-Bootstrap后,引入Button组件页面直接空白,控制台抛出三类错误:
react.development.js:209:Warning: Invalid hook call. Hooks can only be called inside of the body of a function component.react.development.js:1618:Uncaught TypeError: dispatcher is nullreact-dom.development.js:18687:错误源自Button组件
操作流程
- 执行命令初始化项目:
npx create-react-app bootstraptest cd bootstraptest npm install react-bootstrap bootstrap npm start
- 在
App.js中引入Button组件:
import Button from 'react-bootstrap/Button';
- 添加组件代码
<Button>test</Button>后,页面空白并触发上述错误。
问题根源
依赖安装路径错误——bootstrap和react-bootstrap被安装到了React项目目录之外的同级文件夹中,导致项目无法正确加载对应依赖。
依赖文件对比
项目内部package.json(无目标依赖):
{ "name": "boot", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
外部同级目录package.json(含目标依赖):
{ "dependencies": { "bootstrap": "^5.2.3", "react-bootstrap": "^2.7.4" } }
解决办法
- 删除外部目录的
package.json及对应的node_modules文件夹(若存在) - 切换到React项目根目录(
bootstraptest文件夹),重新执行安装命令:
npm install react-bootstrap bootstrap
- 确认项目内部
package.json的dependencies中出现bootstrap和react-bootstrap的版本记录 - 重启项目,组件即可正常渲染
内容的提问来源于stack exchange,提问作者toby
相关产品推荐
相关产品推荐

