react改變css樣式的方法:1、動(dòng)態(tài)添加一個(gè)class來改變樣式,代碼如“<p className={this.state.display?"active":"active1"}></p>”;2、動(dòng)態(tài)添加一個(gè)style來改變樣式,代碼如“<p style={display2}></p>”。
本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
react 怎么改變css樣式?
react的兩種動(dòng)態(tài)改變css樣式的方法
第一種:動(dòng)態(tài)添加class,以點(diǎn)擊按鈕讓文字顯示隱藏為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> {/*動(dòng)態(tài)添加一個(gè)class來改變樣式*/} <p className={this.state.display?"active":"active1"}>你是我的唯一</p> <button onClick={this.handlehide}>點(diǎn)擊隱藏</button> <button onClick={this.handleshow}>點(diǎn)擊顯示</button> </Fragment> ) } handleshow() { this.setState({ display:true }) } handlehide() { this.setState({ display:false }) } } export default Demo;
登錄后復(fù)制
css代碼:
.active{ display: block; } .active1{ display: none; }
登錄后復(fù)制
第二種:動(dòng)態(tài)添加一個(gè)style,以點(diǎn)擊按鈕讓文字顯示隱藏為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> {/*動(dòng)態(tài)添加一個(gè)style來改變樣式*/} <p style={display2}>你是我的唯一</p> <button onClick={this.handlehide2}>點(diǎn)擊隱藏2</button> <button onClick={this.handleshow2}>點(diǎn)擊顯示2</button> </Fragment> ) } handleshow2() { this.setState({ display2:true }) } handlehide2() { this.setState({ display2:false }) } } export default Demo;
登錄后復(fù)制
總結(jié):用class來改變css樣式,可以寫多個(gè)動(dòng)態(tài)改變的css屬性,看起不雜亂,而用style寫的話,如果寫多個(gè)css屬性就會(huì)看起復(fù)雜。都是個(gè)人觀點(diǎn),不足請(qǐng)指出
推薦學(xué)習(xí):《react視頻教程》