How to write CSS elegantly with react

How to write CSS elegantly with react

1. Inline styles

Advantages: This method is relatively simple and clear, adding style attributes to the tag.

Disadvantages: This method can cause the project structure to be bloated and cause CSS naming conflicts.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class index extends Component {
    static propTypes = {
     title: PropTypes.string
    }
    render() {
        const h1Style={textAlign:'center',marginBottom:'20px',lineHeight:'35px',
        height:'30px'}
        const {title} = this.props
        return (
         <div>
             <h1 style={h1Style}>{title}</h1>
             <hr/>
         </div>
        )
    }
}

2. Use import method

Advantages: This method is more flexible to use, similar to the external introduction in CSS

Disadvantages: Because the react style is global by default, it is likely to cause style conflicts

Usage: Create a new css file, set the class name through the className attribute in the jsx syntax, and use the class name in css. This method can use a ternary expression to select the class name by defining a variable.

import React, { Component } from 'react'
import "./index.css"
export default class index extends Component {
    state={
        flag:true
    }
changeColor=()=>{
    this.setState((state, props)=>{
        return {
           flag:!state.flag
        }
    })
}
    render() {
        const {flag}=this.state
        return (
            <div>
                <h1 className={flag?'blueColor':'redColor'}>Don't wait until your hair turns grey</h1>
                <button onClick={this.changeColor} className="btnStyle">Click to change font color</button>
            </div>
        )
    }
}

.blueColor{
    color: blue;
}
.redColor{
    color: red;
}
.btnStyle{
    width: 260px;
    height: 50px;
    background-color: aqua;
    color: #fff;
    border:none;
    font-size: 28px;
    border-radius: 10px;
}

3.css module export

Advantages: No naming conflicts, styles are only valid locally

Disadvantages: Too cumbersome, modules need to be imported and exported every time, which is equivalent to treating all CSS class names as attributes of an object. When the object attribute is needed, the class name is called by calling the object attribute. The way to resolve CSS conflicts is to add prefixes to different class names, similar to setting module for style in Vue.

use:

  • In the cra scaffolding, as long as the css style is introduced in the parent component, then this style is the global style
  • Using modularity to solve style conflicts in react
  • In the cra scaffolding, if a style file needs to be modularized, just name the style file xx.module.css/xx.module.scss

import React,{FC,useState} from "react"
import Cmittem from "@/components1/cmittem"
import cssObj from "./cmtlist.module.scss"
const Cmtlist:FC<{}>=(props)=>{
    return (
        <div>
             <h1 className={cssObj.title}>Comments List</h1>
       
       </div>
    )
}

export default Cmtlist

4. Use styled-components

Advantages: The combination of template string tag + style is a component starting with a capital letter. For example, it can be said that it integrates some of the most popular writing methods in react development. For react developers, it is a very good start. So, in react components, different developers have different habits of using external CSS or component CSS.

use:

Need to install styled-components

npm i styled-components or yarn add styled-components

vscode installation plug-in for easy writing

4.1 Initial Use

import 'antd/dist/antd.less'
import styled from 'styled-components'
function App() {
 const HomeWrapper = styled.div`
 font-size:50px;
 color:red;
 span{
   color:orange;
   &.active{
      color:green;
   }
   &:hover{
     color:blue;
     font-size:40px;
   }
   &::after{
     content:'ssss'
   }
   }
 `
  return (
    <div className="App">
 <h1>I am a title</h1>
 <HomeWrapper>
 <h2>I am a subtitle</h2>
   <span>Carousel 1</span>
   <span className="active">Carousel 2</span>
   <span>Carousel 3</span>
   <span>Carousel 4</span>
 </HomeWrapper>
    </div>
  );
}

export default App;

4.2 Setting attributes through attrs

import 'antd/dist/antd.less'
import styled from 'styled-components'
function App() {
 const ChangeInput = styled.input.attrs({
   placeholder:'wangsu',
   bgColor:'red'
 })`
 background-color:#7a7ab4;
 color:${props=>props.bgColor}
 `
  return (
    <div className="App">
 <h1>I am a title</h1>
 <ChangeInput type="text"/>
    </div>
  );
}

export default App;

4.3 CSS inheritance

import React, { Component } from 'react'
import styled from 'styled-components'
const HYbutton = styled.button`
   color:red;
   border:1px solid #ccc;
   padding:10px 20px;
`
//Here we use inheritance const XLbutton = styled(HYbutton)`
background-color:blue;
`
export default class Button extends Component {

    render() {
        return (
            <div>
                <HYbutton>This is a button</HYbutton>
                <XLbutton>This is an inherited button</XLbutton>
            </div>
        )
    }
}

I have been using this method when developing projects these days. It feels very novel. Although there are disputes in the community, I personally like this method of setting CSS. I don’t have to consider the global style issues at all.

The above is the details of how to write CSS elegantly with react. For more information about writing CSS with react, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • React implementation example using Amap (react-amap)
  • Detailed explanation of virtual DOM and diff algorithm in react
  • React example showing file upload progress
  • How to use lazy loading in react to reduce the first screen loading time
  • How to run the react project on WeChat official account
  • Encapsulate a simplest ErrorBoundary component to handle react exceptions
  • React Fiber structure creation steps
  • Detailed explanation of the use of Refs in React's three major attributes
  • Write a React-like framework from scratch
  • Understanding and using React useEffect

<<:  Perfect solution to the problem of Windows Server 2012 or 2016 failing to install .NET Framework 3.5 without disk

>>:  Summary of common sql statements in Mysql

Recommend

HTML Tutorial: Definition List

<br />Original text: http://andymao.com/andy...

Detailed explanation of CocosCreator message distribution mechanism

Overview This article begins to introduce content...

JS implements user registration interface function

This article example shares the specific code of ...

Node.js sends emails based on STMP protocol and EWS protocol

Table of contents 1 Node.js method of sending ema...

Detailed explanation of the pitfalls of mixing npm and cnpm

Table of contents cause reason Introduction to NP...

Detailed explanation of docker-machine usage

Docker-machine is a Docker management tool offici...

A brief discussion on the VUE uni-app life cycle

Table of contents 1. Application Lifecycle 2. Pag...

A brief discussion on the magical slash in nginx reverse proxy

When configuring nginx reverse proxy, the slashes...

Mobile browser Viewport parameters (web front-end design)

Mobile browsers place web pages in a virtual "...

Use VSCode's Remote-SSH to connect to Linux for remote development

Install Remote-SSH and configure it First open yo...

vue2.x configuration from vue.config.js to project optimization

Table of contents Preface vue.config.js configura...

Introduction to the use of select optgroup tag in html

Occasionally, I need to group select contents. In ...

Solution to the problem of mysql service starting but not connecting

The mysql service is started, but the connection ...