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"。改完后不报错了,但是编译会变慢。如果不改只是报错可能也没什么影响。

效果图:

相关推荐
一叶飘零晋7 小时前
【(一)Electron 使用之如何用vite+vue3搭建初始框架】
前端·javascript·electron
光影少年8 小时前
前端SSR和ssg区别
前端·vue.js·人工智能·学习·react.js
广州华水科技8 小时前
北斗形变监测传感器在水库安全监测中的应用与发展
前端
凯瑟琳.奥古斯特8 小时前
Bootstrap快速上手指南
开发语言·前端·css·bootstrap·html
精益数智工坊8 小时前
拆解制造业仓库物料管理流程:如何通过标准化仓库物料管理流程解决账实不符难题
大数据·前端·数据库·人工智能·精益工程
恶猫8 小时前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
小羊Yveesss9 小时前
2026年前端开发新趋势:智能协同、工具革新与场景深耕
前端·ai
Dxy12393102169 小时前
HTML中的Canvas可以干哪些事情
前端·html
悟乙己9 小时前
解析 Agent 时代的 HTML PPT SKILLS: html-ppt-skill
前端·html·powerpoint
ZC跨境爬虫9 小时前
跟着 MDN 学 HTML day_2:(表单分组与高级输入控件实战)
前端·javascript·css·ui·html