发布于 2026-01-06 6 阅读
0

Tailwind with React DEV 的全球展示挑战赛由 Mux 呈现:展示你的项目!

Tailwind 与 React

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

Tailwind 是一个 CSS 库,类似于 Bootstrap 或 Bulma。不同之处在于,Tailwind 不提供完整的组件 CSS,而是提供底层实用类。这意味着,你无需使用 class="button" 或 "card" 等类名,而是通过组合 Tailwind 的实用类来定义自己的按钮。

例如,我们将分别查看使用 Bootstrap 创建的卡片和使用 Tailwind 创建的卡片的 HTML 代码。

Bootstrap -请查看 CodePen 上的示例

<!-- from the Bootstrap documentation
     https://getbootstrap.com/docs/4.0/components/card/
-->
<div class="card" style="width: 18rem;">
  <img
    class="card-img-top"
    src="https://www.fillmurray.com/300/300"
    alt="Card image cap"
  />
  <div class="card-body">
    <h5 class="card-title">Card title</h5>
    <p class="card-text">
      Some quick example text to build on the card title and make up the bulk of
      the card's content.
    </p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Tailwind -请参阅 CodePen 上的示例

<div class="w-64 rounded overflow-hidden shadow-lg">
  <img
    class="w-full"
    src="https://www.fillmurray.com/300/300"
    alt="Bill Murray Placeholder"
  />
  <div class="px-6 py-4">
    <div class="font-bold text-xl mb-2">Card Title</div>
    <p class="text-gray-700 text-base">
      Some quick example text
    </p>
  </div>
  <div class="px-6 py-4">
    <button class="bg-blue-800 py-2 px-2 rounded text-white">
      Go Somewhere
    </button>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

您可能已经注意到,Tailwind 卡片的 CSS 类属性更加冗长。不过,现在我们无需直接修改 CSS 即可调整组件的外观。

例如,如果我们想给卡片添加背景,我们可以给起始 div 应用 bg-color 类:<div class="w-64 rounded overflow-hidden shadow-lg bg-indigo-300">...</div>bg-indigo-300该类是 Tailwind 实用类的一个例子。

使用 React

我们将从一个默认的 Create React 项目开始。

> npx create-react-app react-tailwind-example
Enter fullscreen mode Exit fullscreen mode

接下来,我们将添加一些依赖项。

> yarn add tailwindcss tailwind.macro@next @emotion/core @emotion/styled
Enter fullscreen mode Exit fullscreen mode

如果您更喜欢 styled-components,您可以将其替换为@emotion/core @emotion/styled

我们准备开始编写一些使用这些库的示例代码。我们将用以下代码替换 App.js:

import React from "react";
import styled from "@emotion/styled";
import tw from "tailwind.macro";

const Button = styled.button`
  ${tw`bg-gray-300 text-yellow-900 px-8 m-8 rounded h-20 text-3xl`}
`;

export default function() {
  return <Button>Testing</Button>;
}
Enter fullscreen mode Exit fullscreen mode

示例输出:

样式化的组件 Button 使用 Tailwind Macrotw来应用实用类,例如背景颜色、圆角、字体大小等。将 Tailwind 与 Emotion 或 Styled-Components 结合使用,可以让我们快速构建灵活的组件。

在我的 React 应用中使用 Tailwind CSS 对我帮助极大。希望它也能对你有所帮助。

文章来源:https://dev.to/ryanlanciaux/tailwind-with-react-2ncl