Next.js项目中styled-components无法获取theme属性问题求助
解决方案
按以下优先级排查修改即可解决:
- 开启Next.js对styled-components的编译支持
Next.js默认没有开启styled-components的服务端渲染兼容配置,首先在项目根目录的next.config.js中添加配置:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { // 开启styled-components编译支持 styledComponents: true, }, } module.exports = nextConfig
如果你使用的是Next.js 12以下版本,需要安装babel-plugin-styled-components,然后在项目根目录新建.babelrc配置文件:
{ "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true }]] }
- 检查styled-components版本一致性
如果项目中同时存在多个版本的styled-components,会导致ThemeProvider和组件内使用的styled实例不匹配,context无法正常传递。执行命令npm ls styled-components(yarn同理)检查版本,确认只有一个版本后,删除node_modules和lock文件重新安装依赖即可。 - 确认ThemeProvider和styled的导入来源一致
如果你项目中使用了react-native-web,组件内的styled.Text是从styled-components/native导入的,那你在_app.tsx中的ThemeProvider也必须从styled-components/native导入,不能使用普通styled-components的ThemeProvider,二者使用的是独立的context实例,无法互通。 - 检查lightTheme的导出导入是否匹配
确认../helpers/light-mode文件中的主题对象导出方式和导入方式一致:
- 如果是默认导出
export default lightTheme,你当前的导入写法正确 - 如果是命名导出
export const lightTheme = {},需要将导入改为import { lightTheme } from '../helpers/light-mode'
- 调整高阶组件包裹顺序
你收到的警告指向被Redux connect包裹的Connect(Front)组件,withTheme需要放在connect的外层,确保context能正常透传:
// 正确写法:withTheme在外层,connect在内层 export default withTheme(connect(mapStateToProps, mapDispatchToProps)(Front))
内容的提问来源于stack exchange,提问作者Lucas Oliveira
相关产品推荐
相关产品推荐

