使用高级 Chakra UI 组件更快地构建 💎

了解更多
跳到内容
文档游乐场指南博客
赞助商

在 Next.js (App) 中使用 Chakra UI

在 Next.js 应用目录中安装 Chakra UI 的指南

模板

使用以下模板之一快速入门。这些模板已正确配置为使用 Chakra UI。

安装

所需的最低 Node 版本为 Node.20.x

1

安装依赖项

npm i @chakra-ui/react @emotion/react
2

添加代码片段

代码片段是预构建的组件,可帮助您更快地构建 UI。使用 @chakra-ui/cli,您可以将代码片段添加到您的项目中。

npx @chakra-ui/cli snippet add
3

更新 tsconfig

如果您使用 TypeScript,您需要更新 tsconfig 文件中的 compilerOptions 以包含以下选项

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "skipLibCheck": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

如果您使用 JavaScript,请创建一个 jsconfig.json 文件并将上述代码添加到该文件中。

4

设置提供程序

在应用程序的根目录中,使用 components/ui/provider 组件中生成的 Provider 组件包装您的应用程序。

此提供程序包含以下内容:

  • 来自 @chakra-ui/reactChakraProvider 用于样式系统
  • 来自 next-themesThemeProvider 用于颜色模式

app/layout.tsx

import { Provider } from "@/components/ui/provider"

export default function RootLayout(props: { children: React.ReactNode }) {
  const { children } = props
  return (
    <html suppressHydrationWarning>
      <body>
        <Provider>{children}</Provider>
      </body>
    </html>
  )
}

需要将 suppressHydrationWarning 属性添加到 html 元素以防止 next-themes 库的警告。

5

优化打包

我们建议在 Next.js 中使用 experimental.optimizePackageImports 功能,通过仅加载您实际使用的模块来优化您的打包大小。

next.config.mjs

export default {
  experimental: {
    optimizePackageImports: ["@chakra-ui/react"],
  },
}

这也有助于解决以下警告:

[webpack.cache.PackFileCacheStrategy] Serializing big strings (xxxkiB)
6

注水错误

如果您看到以下错误:Hydration failed because the initial server rendered HTML did not match the client,且错误类似于

+<div className="chakra-xxx">
-<style data-emotion="css-global xxx" data-s="">

这是由 Next.js 在 --turbo 模式下注水 Emotion CSS 的方式引起的。请从您的 package.json 文件中的 dev 脚本中移除 --turbo 标志。

- "dev": "next dev --turbo"
+ "dev": "next dev"

Next.js 团队修复此问题后,我们将更新此指南。

7

尽情享用!

借助代码片段和 Chakra UI 的基础组件的强大功能,您可以更快地构建 UI。

import { Button, HStack } from "@chakra-ui/react"

const Demo = () => {
  return (
    <HStack>
      <Button>Click me</Button>
      <Button>Click me</Button>
    </HStack>
  )
}

上一个

展示

下一个

Next.js (Pages)