首页 > 解决方案 > 在 react 中为特定组件添加 style.css

问题描述

我正在尝试为 react 中的特定组件添加 CSS 文件,但 CSS 文件适用于所有组件如何为特定组件添加 style.css?

import React, { Component } from "react";
import { Link } from "gatsby";
import Layout from "../components/layout"
import Footer from "../components/Globals/Footer"
import "./crm2.css"


class Crm extends Component {
    render() {
      ...
    }
}

标签: reactjsreact-component

解决方案


Your CSS className must be unique. If you write CSS for this class then it will be applied to the specified component.

There are two components in React

  1. Built-in component (like <p>, <div>, <span>, etc)
  2. React component (like <App/>,<Product>, etc)

React components allows you to break up the UI into different pieces so that it can then be reused and handled individually. It is the Dot-notation component like <UserContext.Provider> and any component which starts with a capital letter.

These components can be styled if you provide a unique className to those components and you write a CSS style for that.

You might have styled the built-in component as shown below

style.css file:

p {
font-size:14px;
color: red;
}

Using the above approach, the CSS would be applied to all the <p> component in all the JSX file.

If you have wanted to style the React component then you need to select those components and styled it as shown below.

<Product className = "items" />

CSS would be

.items {
   color: red;
   ...
}

推荐阅读