在 React JS 中添加 CSS 的不同方法

2025-05-26

在 React JS 中添加 CSS 的不同方法

嗨,大家好!。

在本文中,我们将探讨向 React 应用添加 CSS 代码的最佳方法。
毫无疑问,CSS 在提升应用的用户友好度和视觉吸引力方面发挥着至关重要的作用。向 React 应用添加 CSS 的方法有很多种。让我们来讨论其中几种。

在我的博客上阅读这篇文章


1 - 外部样式表

您可以在项目目录中创建一个新的 CSS 文件,并在其中添加 CSS。然后,您可以将其导入到您的 React 组件或类中。
以下代码用于导入外部 CSS 样式表。



import "./styles.css";


Enter fullscreen mode Exit fullscreen mode

2 - 内联 CSS

内联 CSS 可能是在 React 中添加样式最常见、最快捷的方法。然而,它有几个缺点,通常不建议使用,尤其是在大型应用程序中。

要实现内联 CSS,您可以创建一个包含样式引用的对象,然后使用 style{} 属性调用该对象。
例如:



const styles = {
  section: {
    fontSize: "18px",
    color: "#292b2c",
    backgroundColor: "#fff",
    padding: "0 20px"
  },
  wrapper: {
    textAlign: "center",
    margin: "0 auto",
    marginTop: "50px"
  }
}


Enter fullscreen mode Exit fullscreen mode

然后将其添加到如下元素中:



<section style={styles.section}>
  <div style={styles.wrapper}>
  </div>
</section>


Enter fullscreen mode Exit fullscreen mode

3 - 样式化组件

在我看来,最强大、最实用的可能是 Styled Components。Styled Components 允许你在 JavaScript 中编写真正的 CSS。它的主要优势在于你可以在 CSS 中添加条件代码,并在 CSS 中使用变量和函数。

您可以使用以下命令安装 Styled Components:


 install --save styled-components

Enter fullscreen mode Exit fullscreen mode

接下来,你需要将其导入到你的组件中。然后,你可以创建一个包含 CSS 的新变量。相同的变量名可以用于之前添加样式的 HTML 元素。



import styled from 'styled-components'
// Create a button variable and add CSS
const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid red;
  color:red;
`
//display the HTML
return (
  <div>
    <Button>Button</Button>
  </div>
);


Enter fullscreen mode Exit fullscreen mode
除此之外,还有 3 种更有用的方法可以添加 CSS(感谢 lukeshiru):

4 - CSS模块

您还可以非常轻松地添加范围样式,只需要创建一个扩展名为 .module.css 的文件,如下所示:



// ComponentName.module.css

.Red {
  color: #f00;
}

.Blue {
  color: #00f;
}


Enter fullscreen mode Exit fullscreen mode

然后像这样导入它:



import styles from "./ComponentName.module.css";


Enter fullscreen mode Exit fullscreen mode

像这样使用它:



<span className={styles.Red}>This text will be red</span>
<span className={styles.Blue}>This text will be blue</span>

Enter fullscreen mode Exit fullscreen mode




5 - 原子 CSS

最流行的原子 CSS 框架之一是Tailwind,只需按照其说明将其作为项目的一部分,您就可以使用 classNames,甚至无需触及 CSS。



<button className="font-bold bg-blue-600 px-6 py-3 text-white rounded-md">Blue button</button>

Enter fullscreen mode Exit fullscreen mode




6. 情感

Styled-components 并非唯一一个允许你创建嵌入样式的组件的库,你还有很多其他不错的选择,比如 Emotion。Emotion 最大的优点在于它与框架无关,因此你可以将你的知识运用到 React 之外的其他库和框架中,同时它与 styled-components 非常相似(因此在某些情况下你只需更改导入即可)。


就是这样。我相信还有很多其他的选项,但我认为这些选项已经满足了你在应用中添加 CSS 时的大部分需求。

也请查看我的博客

谢谢!

文章来源:https://dev.to/salehmubahar/3-ways-to-add-css-in-react-js-336f
PREV
JavaScript 中的类
NEXT
JS 数组速查表