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

效果图:

相关推荐
半夜里咳嗽的狼5 分钟前
组件进侧栏就变形?用 CSS Container Queries 把响应式边界收回组件
前端·css
xx240611 分钟前
前端性能优化笔记
前端·笔记·性能优化
带娃的IT创业者17 分钟前
单文件架构的极致美学:深入解析 Bento 的 HTML 幻灯片技术实现
前端·架构·html·web开发·bento·单文件架构
muddjsv20 分钟前
CSS 值的完整计算过程:指定值、计算值、使用值、实际值与动态依赖
前端·css
恋猫de小郭21 分钟前
KotlinLLM 开源 ,一个可以在运行时自己生成永久 Kotlin 代码的 Agent 库
android·前端·人工智能
名字还没想好☜23 分钟前
React createPortal 实战:模态框逃出 overflow:hidden、事件冒泡与焦点管理
前端·javascript·react.js·ecmascript·react·createportal
用户0595401744637 分钟前
Playwright测试AI记忆存储踩坑实录:这个时序问题让我排查了6小时
前端·css
IT_陈寒40 分钟前
Redis踩了个大坑,原来DEL命令也会卡住整个实例
前端·人工智能·后端
一个水瓶座程序猿.1 小时前
基于Spring AI RAG 的AI知识库前端交互实现
前端·人工智能·spring
breeze jiang1 小时前
React + TypeScript 编辑表单:为什么要区分 name 和 editingName
前端·typescript