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

效果图:

相关推荐
汉得数字平台9 分钟前
汉得H-AI飞码——前端编码助手V1.1.2正式发布:融业务知识,提开发效能
前端·人工智能·智能编码
前端小万9 分钟前
Jenkins 打包崩了?罪魁是 package.json 里的 ^
前端·jenkins
编程小白gogogo9 分钟前
苍穹外卖前端环境搭建
前端
shuaijie051811 分钟前
当表格数据量过大的时候,如何使用不分页进行展示
javascript·vue.js·ecmascript
光影少年13 分钟前
web端安全问题有哪些?
前端·安全
行走的陀螺仪20 分钟前
Vite & Webpack 插件/Loader 封装完全指南
前端·webpack·node.js·vite·前端工程化·打包构建
1024肥宅26 分钟前
浏览器网络请求 API:全面解析与高级封装(1)
前端·websocket·axios
小费的部落28 分钟前
Excel 在Sheet3中 匹配Sheet1的A列和Sheet2的A列并处理空内容
java·前端·excel
霍格沃兹测试学院-小舟畅学28 分钟前
Cypress 入门与优势分析:前端自动化测试的新利器
前端
1024肥宅28 分钟前
浏览器网络请求 API:全面解析与高级封装(2)
前端·websocket·axios