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{...}".
#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 ( <Fragment> {/*动态添加一个class来改变样式*/} <p className={this.state.display?"active":"active1"}>你是我的唯一</p> <button onClick={this.handlehide}>点击隐藏</button> <button onClick={this.handleshow}>点击显示</button> </Fragment> ) } 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 ( <Fragment> {/*动态添加一个style来改变样式*/} <p style={display2}>你是我的唯一</p> <button onClick={this.handlehide2}>点击隐藏2</button> <button onClick={this.handleshow2}>点击显示2</button> </Fragment> ) } 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!