React中使用styled-components触发'useContext'错误求助
styled-components 报错:Cannot read properties of null (reading 'useContext') 解决
问题情况
我是React初学者,学习styled-components时编写样式组件代码后,出现Cannot read properties of null (reading 'useContext')错误。执行npm install styled-components时,依赖被安装到了my-app目录外的第二个node_modules文件夹,尝试删除该文件夹、检查App.css链接都无法解决问题。
我的App.js代码如下:
import React, { Component } from 'react'; import styled from 'styled-components'; import './App.css'; class WhoAmI extends Component { constructor(props) { super(props); this.state = { years: 27, position: '' }; } nextYear = () => { this.setState((state) => ({ years: state.years + 1 })); }; commitInputChanges = (e, color) => { console.log(color); this.setState({ position: e.target.value }); }; render() { const { name, surname, link } = this.props; const { position, years } = this.state; return ( <> <button onClick={this.nextYear}>+++</button> <h1> My name is {name}, surname - {surname}, age -{years}, position - {position} </h1> <a href={link}>My profile</a> <form> <span>Введите должность</span> <input type="text" onChange={(e) => { this.commitInputChanges(e, 'some color'); }} /> </form> </> ); } } const Wrapper = styled.div ` width: 600px; margin: 80px auto 0 auto; padding: 20px; `; function App() { return ( <Wrapper> <WhoAmI name="John" surname="Smith" link="facebook.com" /> <WhoAmI name="Alex" surname="Shepard" link="vk.com" /> </Wrapper> ); } export default App;
报错信息:
Cannot read properties of null (reading 'useContext') TypeError: Cannot read properties of null (reading 'useContext') at Object.useContext (http://localhost:3000/static/js/bundle.js:40701:25) at http://localhost:3000/static/js/bundle.js:42407:58 at O (http://localhost:3000/static/js/bundle.js:42432:6) at renderWithHooks (http://localhost:3000/static/js/bundle.js:20020:22) at updateForwardRef (http://localhost:3000/static/js/bundle.js:22589:24) at beginWork (http://localhost:3000/static/js/bundle.js:24636:20) at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:9616:18) at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:9660:20) at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:9717:35) at beginWork$1 (http://localhost:3000/static/js/bundle.js:29581:11)
解决步骤
正确安装依赖到项目目录
打开终端,先切换到React项目根目录(my-app文件夹):cd my-app重新安装styled-components:
npm install styled-components这样依赖会被安装到项目内部的node_modules文件夹,而非上级目录。
清理重复依赖并重新安装
- 删除项目外的多余node_modules文件夹
- 在项目根目录执行:
让npm重新整理所有依赖,确保版本兼容。npm install
确保styled-components版本与React兼容
如果React版本是18+,建议安装最新稳定版的styled-components:npm install styled-components@latest验证组件使用方式
确保styled-components创建的组件(如Wrapper)在React组件内部使用,你的App组件写法没问题,依赖安装正确后即可正常渲染。
报错原因说明
这个错误本质是styled-components无法正确获取React的Context,大概率是依赖安装位置错误,导致项目加载了与当前React版本不兼容的styled-components实例,或依赖未正确集成到项目环境中。
内容的提问来源于stack exchange,提问作者StackTheCode
相关产品推荐
相关产品推荐

