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

Next13中导入GlobalStyles至_app.tsx时出现类型错误求助

解决Next.js 13 + styled-components中GlobalStyles组件类型错误

问题原因

这个类型错误是因为GlobalStyles的类型被错误推断为需要接收TemplateStringsArray类型的props,通常是全局样式组件的定义方式有误,或是依赖类型不匹配导致的。

解决方案

1. 修正GlobalStyles的定义方式

确保你是通过styled-components的createGlobalStyle来创建全局样式组件,而不是普通的styled语法。正确的定义示例:

// styles/global/GlobalStyles.ts
import { createGlobalStyle } from 'styled-components';

export const GlobalStyles = createGlobalStyle`
  /* 在这里编写全局样式 */
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  body {
    font-family: ${props => props.theme.fonts.sans};
    background-color: ${props => props.theme.colors.background};
  }
`;

2. 修复依赖类型冲突

如果已经正确使用了createGlobalStyle仍报错,尝试以下步骤:

  • 确认@types/styled-components的版本与styled-components版本兼容(建议保持同版本号范围)
  • 删除node_modules、package-lock.json(或yarn.lock),重新执行npm install(或yarn install)
  • 重启TypeScript语言服务(VSCode中可按Ctrl+Shift+P,选择「TypeScript: Restart TS Server」)

3. 适配Next.js 13路由模式

如果使用的是Next.js 13的App Router模式,建议将全局样式组件移至app/layout.tsx中(替代原_app.tsx的作用),示例:

// app/layout.tsx
import { ThemeProvider } from 'styled-components';
import { GlobalStyles } from '../styles/global/GlobalStyles';
import theme from '../styles/theme';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <ThemeProvider theme={theme}>
          <GlobalStyles />
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

内容的提问来源于stack exchange,提问作者Otoniel Emanuel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:12:40