【React】React + Tailwind CSS 快速入门指南

Tailwind CSS 是一个功能强大实用优先的 CSS 原子性的库,可以帮助你快速构建现代化的用户界面。

它支持的种类框架也非常的多! 例如: ViteNext.js 等...

这个库给我们带来的好处就是可以给我们衍生出其他增强的体验!

比如说 shadcn/uidaisyUI 无样式 UI 库!这些 UI 库就是基于 Tailwind CSS 适配开发的!

参考: tailwindcss 官网

以下是安装和使用 Tailwind CSS 的步骤:

1.创建一个 React 项目

bash 复制代码
npm create vite@latest my-project -- --template react

cd my-project

2.安装 Tailwind CSS

2.1 首先,你需要在项目中安装 tailwindcss及其对等依赖 !

bash 复制代码
// 1.安装 Tailwind CSS
npm install -D tailwindcss@3.4.17

// 2.安装对等依赖 
npm install -D postcss autoprefixer

ps: 安装时我们要指定版本安装 与官网文档版本保持一致即可! 如果不指定版本、默认安装是就是 v4 版本的 tailwindcss

当你继续执行 npx tailwindcss init 就会报错, 没有可执行文件的信息!

bash 复制代码
PS D:\lx\project\emoji-picker> npx tailwindcss init
npm ERR! could not determine executable to run

npm ERR! A complete log of this run can be found in: C:\Users\AppData\Local\npm-cache\_logs\2025-03-08T04_37_23_510Z-debug-0.log

解决方式: 我们安装切换官网的版本下载安装即可解决。

bash 复制代码
npm install -D tailwindcss@3.4.17

3. 初始化 Tailwind CSS 配置文件

3.1 安装完成后,你可以通过以下命令生成 tailwind.config.jspostcss.config.js 配置文件:

因为要分析我们的代码, 把 Tailwind CSS的代码指令, 编译成浏览器可以识别的 CSS。

bash 复制代码
npx tailwindcss init -p

3.2 将这些路径添加到 tailwind.config.js 文件中的所有模板文件中。

tailwind.config.js 文件允许你自定义 Tailwind 的默认配置,例如颜色、字体、间距等。

js 复制代码
/** @type {import('tailwindcss').Config} */
export default {
 // 指定项目目录下那些文件需要处理! 
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

4. 创建 Tailwind CSS 入口文件

在你的项目中入口 CSS 文中引入 Tailwind 的基础样式、组件和工具类:
例如: src/index.css

css 复制代码
@tailwind base;
@tailwind components;
@tailwind utilities;

ps: 且必须在你的项目入口 main.js 文件中将 index.css 文件引入到全局。

5. 在你的页面代码中使用 Tailwind CSS

tsx 复制代码
function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <button className='text-pink-400 px-2 py-2 bg-slate-600 rounded'> Hello World </button>
    </>
  )
}

export default App

6. Vs CodeTailwind CSS 扩展插件

直接在 扩展商店直接安装下载即可。 它可以触发 Tailwind CSS 提示片段。

bash 复制代码
Tailwind CSS IntelliSense

7.总结

  • 一个好的扩展包,一个好的框架也好 ! 往往是因为它的产生,而影响起来的生态!让咱们可以加快开发速度!
  • 如果你有更多问题,欢迎随时问我!😊
相关推荐
崽崽的谷雨2 小时前
react实现一个列表的拖拽排序(react实现拖拽)
前端·react.js·前端框架
ziyu_jia4 小时前
React 组件测试【React Testing Library】
前端·react.js·前端框架
祈澈菇凉4 小时前
如何在 React 中实现错误边界?
前端·react.js·前端框架
撸码到无法自拔4 小时前
❤React-组件的新旧生命周期
前端·javascript·react.js·前端框架·ecmascript
WangYan20226 小时前
ArcGIS水文水资源水环境应用实战:从入门到精通!ArcGIS水文分析及流域特征提取;湖泊水库水环境监测及评价;河道水污染预测与水环境容量计算等
arcgis·水文分析·水环境·水文·水资源
alpha_xiao6 小时前
css 知识点整理
前端·css
江西谢霆锋6 小时前
css -学习
前端·css·学习
qianmoQ6 小时前
第一章:Tailwind CSS基础与项目设置 - 第一节:Tailwind CSS入门 - 核心理念与工作流
前端·css