首頁 > web前端 > css教學 > 主體

在 React 專案中實作 CSS 模組

Susan Sarandon
發布: 2024-09-30 14:12:03
原創
910 人瀏覽過

Implementing CSS Modules in Your React Project

CSS Modules in React are a way to scope CSS by automatically generating unique class names. This prevents class name collisions in large applications and allows for modular styles. Here's how you can use CSS Modules in a React project:

1. Setup

By default, React supports CSS Modules. You just need to name your CSS file with the extension .module.css.

2. Example Setup

File Structure:

src/
├── components/
│   ├── Button.js
│   ├── Button.module.css
登入後複製

Button.module.css:

.button {
  background-color: #6200ea;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button:hover {
  background-color: #3700b3;
}
登入後複製

Button.js:

import React from 'react';
import styles from './Button.module.css';

const Button = () => {
  return (
    <button className={styles.button}>
      Click Me
    </button>
  );
}

export default Button;
登入後複製

How It Works:

  • Button.module.css: You define CSS rules like any normal CSS file.
  • styles.button: The class names from the CSS module are imported as a JavaScript object. You reference them using styles.className.

Benefits:

  • Scoped styles: Each class is locally scoped to the component, avoiding name collisions.
  • Maintainability: As your application grows, your CSS remains modular and easier to manage.

Let me know if you need help with specific cases!

以上是在 React 專案中實作 CSS 模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!