tailwind css_如何使用Tailwind CSS,样式化的组件和Twin Macro用更少的代码来样式化您的React应用

tailwind css

Tailwind is a utility-first CSS framework for rapidly building custom designs. It can be used alone to style React Apps. However, it can be better combined with Styled Components. That combination brings the magic of Tailwind into CSS-in-JS.

Tailwind是实用程序优先CSS框架,用于快速构建自定义设计。 可以单独使用它来设置React Apps的样式。 但是,最好将其与样式化组件结合使用。 这种结合将Tailwind的魔力带入了CSS-in-JS。

In this guide, we will build a form component without writing a single line of CSS using Tailwind CSS, Styled Components, and Twin Macro.

在本指南中,我们将构建表单组件,而无需使用Tailwind CSS,样式化组件和Twin Macro编写一行CSS。

Let's dive in!

让我们潜入吧!

为什么要使用它? (Why use it?)

The "Why" is pretty legit and important, since we can use either Tailwind CSS or Styled Components. So why combine them and use both at the same time?

“为什么”非常合法且重要,因为我们可以使用Tailwind CSS或样式化组件。 那么,为什么要将它们组合在一起同时使用呢?

Well, Tailwind classes can be quite long, and it causes our components to have some readability issues. Maintaining them can be tough.

好吧,Tailwind类可能很长,这导致我们的组件存在一些可读性问题。 维护它们可能很困难。

In the case of Styled Components, there is no problem except the fact that we have to write the style. It is not that problematic – but why should we write something that Tailwind already offers?

对于样式化组件,除了必须编写样式这一事实外,没有任何问题。 这不是问题,但是为什么我们要写Tailwind已经提供的东西呢?

So it makes sense to use Tailwind CSS in combination with Styled Components. Tailwind CSS helps with utility classes, and Styled Components keeps our components clean with the help of CSS-in-JS.

因此,将Tailwind CSS与样式化组件结合使用是有意义的。 Tailwind CSS帮助实用程序类,而Styled Components借助CSS-in-JS使我们的组件保持清洁。

配置 (Setting up)

In this guide, we will build a simple form as an example. And to do so, we need a fresh React app.

在本指南中,我们将构建一个简单的表格作为示例。 为此,我们需要一个新的React应用程序。

So, let's run in the terminal the following command.

因此,让我们在终端中运行以下命令。

npx create-react-app react-styled-tailwind

Next, structure your folder as follows:

接下来,按如下所示构造文件夹:

├── 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

I will explain each file as we progress, but for now, let's install the dependencies.

我将在进行过程中解释每个文件,但现在,让我们安装依赖项。

yarn add -D tailwindcss twin.macro autoprefixer babel-plugin-macros postcss-cli

Next, install Styled Components by running this command:

接下来,通过运行以下命令来安装样式化组件:

yarn add styled-components

Once these libraries are installed, we can now move to the configuration of Tailwind CSS

安装这些库之后,我们现在可以转到Tailwind CSS的配置

配置Tailwind CSS (Configuring Tailwind CSS)

To configure it, we have to manually add a config file or run the following command to generate a new one:

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

npx tailwind init src/tailwind.config.js

Here, instead of generating the config file on the root directory, you have to put it on the src folder – otherwise an error will be thrown by Tailwind Macro.

在这里,不必在根目录上生成配置文件,而必须将其放在src文件夹中–否则,Tailwind Macro将引发错误。

And the generated file will look like this:

生成的文件将如下所示:

  • tailwind.config.js

    tailwind.config.js

module.exports = {
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

As you can see, the config file is "empty" since there is no configuration. For this tutorial, we don't need to configure anything here. But you can customize it to follow your needs or run the command with the --full option to get the complete Tailwind config.

如您所见,由于没有配置,因此配置文件为“空”。 对于本教程,我们无需在此处进行任何配置。 但是您可以根据需要对其进行自定义,或者使用--full选项运行命令以获取完整的Tailwind配置。

Next, we need to create a new file postcss.config.js in the root directory.

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

  • postcss.config.js

    postcss.config.js

module.exports = {
  plugins: [
    require("tailwindcss")("./src/tailwind.config.js"),
    require("autoprefixer"),
  ],
}

This configuration tells the postcss.config.js file to use the Tailwind CSS library and the tailwind.config.js file during compile-time. With the help of autoprefixer it tracks which properties need to be prefixed.

这种配置告诉postcss.config.js文件使用的Tailwind CSS库和tailwind.config.js在编译时文件。 借助自动前缀autoprefixer它可以跟踪需要添加前缀的属性。

With that setup, we can now move to the babel.plugin.js file which helps to transform Tailwind classes into CSS-in-JS code.

通过该设置,我们现在可以移至babel.plugin.js文件,该文件有助于将Tailwind类转换为CSS-in-JS代码。

  • babel.plugin.js

    babel.plugin.js

module.exports = {
  tailwind: {
    plugins: ["macros"],
    config: "./src/tailwind.config.js",
    format: "auto",
  },
}

Later we will see in action what this file does. But for now, just keep in mind that it's the glue between Tailwind CSS and Styled Components.

稍后我们将看到该文件的作用。 但是现在,请记住,这是Tailwind CSS和样式化组件之间的粘合剂。

There are just three last steps to do to complete the setup.

仅需完成最后三个步骤即可完成设置。

First, in the tailwind.css file, we need to import some utilities from the Tailwind library.

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

  • src/assets/tailwind.css

    src/assets/tailwind.css

@tailwind base;

@tailwind components;

@tailwind utilities;

Here, as you can see, there is nothing fancy, just some imports that allow us to use Tailwind utility classes.

如您所见,这里没有什么幻想,只有一些导入使我们能够使用Tailwind实用程序类。

The second step is to connect our React App with Tailwind CSS.

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

  • index.js

    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()

Here, we import assets/styles.css which contains the CSS style. And later, we will tweak the default script a bit to build the CSS and add it to the assets/styles.css file during compile.

在这里,我们导入包含CSS样式的assets/styles.css 。 然后,我们将稍微调整默认脚本以构建CSS,然后在编译期间将其添加到assets/styles.css文件中。

And last but not the least, we have to update the package.json file.

最后但并非最不重要的一点,我们必须更新package.json文件。

  • 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"
 }

These two scripts build:css and watch:css will respectively build the CSS and watch for changes and rebuild it if needed. And as I said earlier, the output file will be located in the assets folder.

这两个脚本build:csswatch:css将分别构建CSS并监视更改并在需要时对其进行重建。 正如我之前说的,输出文件将位于assets文件夹中。

With that change, we can now use Tailwind in our app. Let's now combine it with Styled Components.

有了这一更改,我们现在可以在应用程序中使用Tailwind。 现在,将其与样式化组件结合起来。

Tailwind CSS和样式化的组件 (Tailwind CSS and Styled Components)

Earlier, in our structure folder, we had a styles folder. It's time to tweak it with the following code.

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

  • styles/index.js

    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

We start by importing tw which allows us to use Tailwind classes in nested properties. It's perfectly fine to use the utility classes with the className attribute, but if you want to nest properties you have to use the twin.macro library.

我们从导入tw开始,这允许我们在嵌套属性中使用Tailwind类。 最好将实用程序类与className属性一起使用,但如果要嵌套属性,则必须使用twin.macro库。

This library will use the babel plugin macros config (babel.plugin.js) to transform the Tailwind CSS utility classes used by nested selectors into readable code that Styled Components can understand.

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

You can see in this example below how the transformation is done.

您可以在下面的示例中看到转换的完成方式。

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

Great! Now that we have combined Tailwind with Styled Components, let's add the styled component to the App.js file.

大! 现在,我们已将Tailwind与样式化组件结合在一起,让我们将样式化组件添加到App.js文件中。

  • 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

Here, we just imported the styled component and wrapped everything with it to make our form look nice.

在这里,我们只是导入了样式化的组件,并用它包装了所有内容,以使我们的表单看起来不错。

Great! You can already see how powerful this combination is. We have built a form component without writing a line of CSS and the component is still readable.

大! 您已经了解了这种组合的强大功能。 我们已经构建了一个表单组件,而没有编写CSS线,并且该组件仍然可读。

结论 (Conclusion)

There is a bit of hassle to set up Tailwind CSS. But once it's done and combined with CSS-in-JS, it's really powerful and flexible. This is partly because we can customize the tailwind.config.js file to follow our need or just write normal CSS as we usually do with Styled Components. It's definitely something to consider in your next React app.

设置Tailwind CSS有点麻烦。 但是,一旦完成并与CSS-in-JS结合使用,它便会变得强大而灵活。 这部分是因为我们可以自定义tailwind.config.js文件来满足我们的需要,或者像我们通常使用样式化组件一样编写普通CSS。 在您的下一个React应用程序中绝对是要考虑的事情。

Thanks for reading!

谢谢阅读!

You can find the Source Code here.

您可以在此处找到源代码

Read more of my articles

阅读更多我的文章

Subscribe to my newsletter

订阅我的时事通讯

Follow me on twitter

在推特上关注我

资源资源 (Resources)

Tailwind CSS Docs

Tailwind CSS文件

Tailwind CSS Cheat sheet

Tailwind CSS作弊表

Twin Macro Docs

双宏文档

Styled Components Docs

样式化组件文档

翻译自: https://www.freecodecamp.org/news/how-to-style-your-react-apps-with-less-code-using-tailwind-css-and-styled-components/

tailwind css

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值