第一種:動態添加class,以點擊按鈕讓文字顯示隱藏為demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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代碼:
1
2
3
4
5
6
|
.active{ display : block ; } .active 1 { display : none ; } |
第二種:動態添加一個style,以點擊按鈕讓文字顯示隱藏為demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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; |
總結:用class來改變css樣式,可以寫多個動態改變的css屬性,看起不雜亂,而用style寫的話,如果寫多個css屬性就會看起復雜。都是個人觀點,不足請指出
到此這篇關于詳解react的兩種動態改變css樣式的方法的文章就介紹到這了,更多相關react動態改變css樣式內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qcg14774125/article/details/89185603