发布于 2026-01-05 0 阅读
0

如何使用 Tailwind CSS、Styled Components 和 Twin Macro 为 React 应用编写更少的代码

如何使用 Tailwind CSS、Styled Components 和 Twin Macro 为 React 应用编写更少的代码

Tailwind 是一个实用性优先的 CSS 框架,用于快速构建自定义设计。它可以单独用于 React 应用的样式设计。不过,它与 Styled Components 结合使用效果更佳。这种组合将 Tailwind 的强大功能融入了 CSS-in-JS 中。

在本指南中,我们将使用 Tailwind CSS、Styled Components 和 Twin Macro 构建一个表单组件,而无需编写任何 CSS 代码。

让我们开始吧!

为什么要使用它?

这个问题的“原因”非常合理且重要,因为我们既可以使用 Tailwind CSS,也可以使用 Styled Components。那么,为什么要将它们结合起来同时使用呢?这是因为
Tailwind CSS 的类名可能很长,这会导致组件的可读性出现问题,而且维护起来也比较困难。

对于 Styled Components 来说,唯一的问题是我们需要自己编写样式。这倒不是什么大问题——但为什么我们要自己写 Tailwind 已经提供的功能呢?

因此,将 Tailwind CSS 与 Styled Components 结合使用是合理的。Tailwind CSS 有助于创建实用类,而 Styled Components 则借助 CSS-in-JS 技术保持组件的简洁性。

设置

在本指南中,我们将以创建一个简单的表单为例进行说明。为此,我们需要一个全新的 React 应用。
那么,让我们在终端中运行以下命令。

    npx create-react-app react-styled-tailwind
Enter fullscreen mode Exit fullscreen mode

接下来,请按如下方式构建文件夹:

├── src
|  ├── App.js
|  ├── App.test.js
|  ├── assets
|  |  └── tailwind.css
|  ├── index.js
|  ├── serviceWorker.js
|  ├── setupTests.js
|  ├── tailwind.config.js
|  └── styles
|     └── index.js
├── babel.plugin.js
├── package.json
├── postcss.config.js
├── README.md
├── yarn-error.log
└── yarn.lock
Enter fullscreen mode Exit fullscreen mode

我会随着讲解的进行逐个解释每个文件,但现在,让我们先安装依赖项。

    yarn add -D tailwindcss twin.macro autoprefixer babel-plugin-macros postcss-cli
Enter fullscreen mode Exit fullscreen mode

接下来,运行以下命令安装 Styled Components。

    yarn add styled-components
Enter fullscreen mode Exit fullscreen mode

安装完这些库之后,我们现在可以开始配置 Tailwind CSS 了。

配置 Tailwind CSS

要进行配置,我们需要手动添加配置文件,或者运行以下命令生成一个新配置文件:

    npx tailwind init src/tailwind.config.js
Enter fullscreen mode Exit fullscreen mode

在这里,您不能在根目录下生成配置文件,而应该将其放在src文件夹中——否则 Twin Macro 会抛出错误。

生成的文件将如下所示。

  • tailwind.config.js
module.exports = {
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

如您所见,配置文件为空,因为没有任何配置。在本教程中,我们不需要进行任何配置。但您可以根据需要进行自定义,或者运行带有相应--full选项的命令以获取完整的 Tailwind 配置。

接下来,我们需要postcss.config.js在根目录下创建一个新文件。

  • postcss.config.js
module.exports = {
  plugins: [
    require("tailwindcss")("./src/tailwind.config.js"),
    require("autoprefixer"),
  ],
}
Enter fullscreen mode Exit fullscreen mode

此配置指示postcss.config.js文件在编译时使用 Tailwind CSS 库tailwind.config.js。它还能帮助autoprefixer跟踪哪些属性需要添加前缀。

完成上述设置后,我们现在可以转到 babel.plugin.js 文件,该文件有助于将 Tailwind 类转换为 CSS-in-JS 代码。

  • babel.plugin.js
module.exports = {
  tailwind: {
    plugins: ["macros"],
    config: "./src/tailwind.config.js",
    format: "auto",
  },
}
Enter fullscreen mode Exit fullscreen mode

稍后我们会实际看到这个文件的作用。但现在,你只需要记住它是 Tailwind CSS 和 Styled Components 之间的桥梁。

设置过程还剩最后三个步骤即可完成。

仍然

首先,在tailwind.css文件中,我们需要从 Tailwind 库导入一些实用程序。

  • src/assets/tailwind.css
@tailwind base;

@tailwind components;

@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

如您所见,这里没有什么花哨的东西,只是一些导入语句,使我们能够使用 Tailwind 实用程序类。

第二步是将我们的 React 应用与 Tailwind CSS 连接起来。

  • index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import "./assets/styles.css"
import * as serviceWorker from "./serviceWorker"

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
)

serviceWorker.unregister()
Enter fullscreen mode Exit fullscreen mode

这里,我们导入assets/styles.css包含 CSS 样式的文件。稍后,我们将对默认脚本进行一些调整,以便assets/styles.css在编译时生成 CSS 并将其添加到文件中。

最后,我们还需要更新package.json文件。

  • package.json
"scripts": {
    "build:css": "postcss src/assets/tailwind.css -o src/assets/styles.css",
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/styles.css",
    "start": "npm run watch:css & react-scripts start",
    "build": "npm run build:css react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
 }
Enter fullscreen mode Exit fullscreen mode

这两个脚本build:css分别watch:css用于构建 CSS 和监视 CSS 更改,并在需要时重新构建。正如我之前提到的,输出文件将位于该assets文件夹中。

经过这项更改,我们现在可以在应用程序中使用 Tailwind 了。接下来,让我们将其与 Styled Components 结合使用。

Tailwind CSS + Styled Components

之前,在我们的结构文件夹中,我们有一个styles文件夹。现在需要用以下代码对其进行调整。

  • styles/index.js
import styled from "styled-components"
import tw from "twin.macro"

const StyledForm = styled.main.attrs({
  className: "flex flex-col h-screen justify-center items-center bg-gray-100",
})`
  & {
    form {
      ${tw`bg-white text-center rounded py-8 px-5 shadow max-w-xs`}
    }
    input {
      ${tw`border-gray-300 mb-4 w-full border-solid border rounded py-2 px-4`}
    }
    button {
      ${tw`bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 border border-blue-700 rounded`}
    }
  }
`
export default StyledForm
Enter fullscreen mode Exit fullscreen mode

首先,我们需要导入twTailwind 库,它允许我们在嵌套属性中使用 Tailwind 类。使用带有className属性的实用类完全没问题,但如果要嵌套属性,则必须使用该twin.macro库。

该库将使用 babel 插件宏配置(babel.plugin.js)将嵌套选择器使用的 Tailwind CSS 实用类转换为 Styled Components 可以理解的可读代码。

您可以在下面的示例中看到转换是如何进行的。

// input
const test = ${tw`text-center bg-red w-full`}
// output
const test = {
    background: 'red',
    textAlign: 'center',
    width: '100%'
}
Enter fullscreen mode Exit fullscreen mode

太棒了!既然我们已经将 Tailwind 与 Styled Components 结合使用,让我们把 styled component 添加到App.js文件中。

  • App.js
import React from "react"
import StyledForm from "./styles"

function App() {
  return (
    <StyledForm>
      <form>
        <input type="text" placeholder="Full name" />
        <input type="text" placeholder="Email" />
        <input type="text" placeholder="Password" />
        <button>Sign In</button>
      </form>
    </StyledForm>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

在这里,我们只是导入了样式组件,并用它包裹了所有内容,使我们的表单看起来更美观。

插图

太棒了!你已经能感受到这种组合的强大之处了。我们构建了一个表单组件,而且无需编写任何 CSS 代码,组件依然清晰易读。

结论

配置 Tailwind CSS 的确有点麻烦,但一旦配置完成并结合 CSS-in-JS,它就非常强大且灵活。这部分原因在于我们可以tailwind.config.js根据需要自定义文件,或者像使用 Styled Components 一样编写普通的 CSS。在开发下一个 React 应用时,这绝对值得考虑。

感谢阅读!

您可以在这里找到源代码。

资源

Tailwind CSS 文档

Tailwind CSS 速查表

双宏文档

Styled Components 文档

文章来源:https://dev.to/ibrahima92/how-to-style-your-react-apps-with-less-code-using-tailwind-css-and-styled-components-301a