Shadcn:可定制的开源 UI
什么是 shadcn? 🤔
Shadcn 在众多 UI 框架和库中脱颖而出,对于寻求开源、可自定义方式来创建令人惊叹且有用的用户界面的开发人员来说,它是一个有用的资源。Shadcn 是一种帮助您构建组件库的工具。这些是您可以复制并粘贴到应用程序中的组件。
它不是组件库,这意味着您不会将其作为 npm 等包管理器的依赖项安装。Shadcn 提供了漂亮的 UI 组件,这些组件可以作为代码直接添加到您的应用程序中,您可以随心所欲地自定义它。
如何在 React 项目中安装 shadcn?
首先使用 :vite
npm create vite@latest shadcn-app -- --template react-ts
或者,如果您使用的是 yarn:
yarn create vite shadcn-app --template react-ts
现在通过运行进入应用程序:
cd shadcn-app
通过运行以下命令安装所有依赖项:
npm install
或者,如果您使用的是 yarn:
yarn
install 及其依赖项,然后生成 and 文件:tailwindcss
tailwind.config.js
postcss.config.js
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
或者,如果您使用的是 yarn:
yarn add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
编辑文件tsconfig.json
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}
现在运行以下命令,以便您可以正确导入 “path”:
npm i -D @types/node
将以下内容添加到,以便您的应用程序可以正确解析路径:vite.config.ts
import path from "path"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})
现在运行 shadcn-ui init 命令来设置项目:
npx shadcn-ui@latest init
或者,如果您使用的是 yarn:
npx shadcn-ui@latest init
运行此作后,系统会提示您几个问题,您可以根据自己的喜好回答这些问题,也可以按照我的喜好回答,如图所示:
就是这样! 现在,我们可以轻而易举地将组件添加到我们的应用程序中! 🎉shadcn
shadcn 为我们提供了大量可以添加的组件列表,您可以在此处找到列表。从 Accordion 一直到 tooltips,我们几乎拥有设计出色的项目中使用的几乎所有组件。
在本文中,我将向您展示如何使用 .您也可以尝试添加其他组件!shadcn
要添加按钮组件,让我们运行:
npx shadcn-ui@latest add button
或者,如果您使用的是 yarn:
npx shadcn-ui@latest add button
要添加警报对话框组件,请运行:
npx shadcn-ui@latest add alert-dialog
of (如果您使用的是 yarn):
npx shadcn-ui@latest add alert-dialog
将 更改为:App.tsx
import { useState } from "react";
import "./App.css";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
function App() {
const [count, setCount] = useState(0);
return (
Vite + React
Something here?
This action cannot be undone. This action is harmful.
Cancel
Continue
);
}
export default App;
您应该看到如下内容:
在这里,我们使用 shadcn 按钮来控制警报,并使用该按钮来增加状态。count
支持其他框架:
除了 React,shadcn 还支持多个其他框架,包括 Next.js 和 Astro 等。你可以在这里找到更多信息。
Shadcn 还提供各种主题和颜色自定义,以更好地满足您的设计需求。这是一个非常直观且对开发人员友好的工具,如果您还没有,您应该立即开始使用!