Next.js 怎么使用 Chakra UI

创建 next.js 的 react 项目

复制代码
npx create-next-app@latest

? What is your project named? >> next-app

之后的选项按自己需要选择

http://localhost:3000 打开网站查看是否正常显示

安装 @chakra-ui

官方文档

复制代码
npm i @chakra-ui/react @emotion/react

Add snippets 这步可以不用做,国内网络好像安装不上。

创建 src\components\ui\provider.tsx

复制代码
"use client";

import { ChakraProvider, defaultSystem } from "@chakra-ui/react";
export function Provider({ children }: { children: React.ReactNode }) {
  return <ChakraProvider value={defaultSystem}>{children}</ChakraProvider>;
}

修改 src\app\layout.tsx

复制代码
import { Provider } from "../components/ui/provider";

  return (
    <html lang="en" suppressHydrationWarning>
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <Provider>{children}</Provider>
      </body>
    </html>
  );

需要向 html 元素添加 suppressHydrationWarning 属性,以防止出现关于 next-themes 库的警告。

用 Provider 包裹元素才能使用组件。

创建 src\app\chakra.tsx

复制代码
import { Button, Stack, Highlight, Switch } from "@chakra-ui/react";
export default function Demo() {
  return (
    <Stack>
      <Switch.Root>
        <Switch.HiddenInput />
        <Switch.Control />
        <Switch.Label>Activate Chakra</Switch.Label>
      </Switch.Root>
      <Highlight
        query="spotlight"
        styles={{ px: "0.5", bg: "orange.subtle", color: "orange.fg" }}
      >
        With the Highlight component, you can spotlight words.
      </Highlight>
      <Button>Click me</Button>
    </Stack>
  );
}

src\app\page.tsx 中引入组件

复制代码
import Chakra from './chakra'
<Chakra />

现在启动报错:Hydration errors

If you see an error like this: Hydration failed because the initial server rendered HTML did not match the client, and the error looks similar to:

This is caused by how Next.js hydrates Emotion CSS in --turbo mode. Please remove the --turbo flag from your dev script in your package.json file.

是因为用 -turbo 的原因,可以将 package.json 里的 "dev": "next dev --turbopack" 改为 "dev": "next dev"。改完后不报错了,但是编译会变慢。如果不改只是报错可能也没什么影响。

效果图:

相关推荐
pe7er5 分钟前
Tauri 应用打包与签名简易指南
前端
前端搬砖仔噜啦噜啦嘞7 分钟前
Cursor AI 编辑器入门教程和实战
前端·架构
Jimmy21 分钟前
TypeScript 泛型:2025 年终极指南
前端·javascript·typescript
来来走走26 分钟前
Flutter dart运算符
android·前端·flutter
Spider_Man29 分钟前
栈中藏玄机:从温度到雨水,单调栈的逆袭之路
javascript·算法·leetcode
moddy31 分钟前
新人怎么去做低代码,并且去使用?
前端
风清云淡_A31 分钟前
【Flutter3.8x】flutter从入门到实战基础教程(五):Material Icons图标的使用
前端·flutter
安心不心安36 分钟前
React ahooks——副作用类hooks之useThrottleEffect
前端·react.js·前端框架
jstart千语38 分钟前
【vue】创建响应式数据ref和reactive的区别
前端·javascript·vue.js
肖师叔爱抽风1 小时前
使用nvm use切换版本时出现虚假成功信息,使用nvm ls,实际显示没有切换成功,解决方法
前端