react怎麼改變css樣式

藏色散人
發布: 2022-12-20 14:53:21
原創
2033 人瀏覽過

react改變css樣式的方法:1.動態加入class,程式碼如「handleshow() {this.setState({display:true})}...」;2.動態新增一個style,程式碼如「class Demo extends Component{...}」。

react怎麼改變css樣式

本教學操作環境:Windows10系統、react18版、Dell G3電腦。

react怎麼改變css樣式? ?

react的兩種動態改變css樣式的方法

第一種:動態新增class,以點選按鈕讓文字顯示隱藏為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程式碼:

 .active{
      display: block;
  }
  .active1{
    display: none;
  }
登入後複製

第二種:動態新增一個style,以點擊按鈕讓文字顯示隱藏為demo

import React, { Component, Fragment } from &#39;react&#39;;
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 ? &#39;block&#39; : &#39;none&#39;
        }
        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影片教學

以上是react怎麼改變css樣式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!