Home  >  Article  >  Web Front-end  >  How to change css style in react

How to change css style in react

藏色散人
藏色散人Original
2022-12-20 14:53:211941browse

How to change CSS style in react: 1. Dynamically add a class, code such as "handleshow() {this.setState({display:true})}..."; 2. Dynamically add a style, code Such as "class Demo extends Component{...}".

How to change css style in react

#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.

How to change css style in react? ?

Two ways to dynamically change css styles in react

The first one: dynamically add a class to click the button to display and hide the text as demo

import React, { Component, Fragment } from 'react';
import './style.css';
class Demo extends Component{
    constructor(props) {
        super(props);
        this.state = {
            display: true
        }
        this.handleshow = this.handleshow.bind(this)
        this.handlehide = this.handlehide.bind(this)
    }
    render() {
        return (
            
                {/*动态添加一个class来改变样式*/}
                

你是我的唯一

) } handleshow() { this.setState({ display:true }) } handlehide() { this.setState({ display:false }) } } export default Demo;

css Code:

 .active{
      display: block;
  }
  .active1{
    display: none;
  }

Second: add a style dynamically, click the button to display and hide the text as demo

import React, { Component, Fragment } from 'react';
class Demo extends Component{
    constructor(props) {
        super(props);
        this.state = {
            display2: true
        }
        this.handleshow2 = this.handleshow2.bind(this)
        this.handlehide2 = this.handlehide2.bind(this)
    }
    render() {
        const display2 = {
            display:this.state.display2 ? 'block' : 'none'
        }
        return (
            
                 {/*动态添加一个style来改变样式*/}
                 

你是我的唯一

) } handleshow2() { this.setState({ display2:true }) } handlehide2() { this.setState({ display2:false }) } } export default Demo;

Summary: use class to change css style, you can write multiple dynamic changes CSS attributes don’t look messy, but when written in style, writing multiple CSS attributes will look complicated. These are all personal opinions, please point out any shortcomings

Recommended study: "react video tutorial"

The above is the detailed content of How to change css style in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn