react學習筆記(四)style綁定&class綁定

react --style綁定

style字面量對象綁定

// state數據
  this.state = {
            a:10,
            b:20,
            txtColor:"#ff0000"
        }
  //屬性綁定
<p style={{color:this.state.txtColor,fontWeight:"bold"}}>react中的style屬性可以綁定一個對象。</p>

style方法綁定

//方法綁定
<p style={this.txtStyleObj()}>style屬性可以綁定一個對象字面量,也可以綁定一個方法調用,方法中返回style對象。</p>

 txtStyleObj = e=>{
        return {
            border:"solid 1px "+this.state.txtColor,
            fontSize:"30px"
        }
    }

react-- class綁定

  {/* react中的className如果需要綁定數組,需要調用數組的join方法,然後綁定 */}
<p className={["MyCom-bgcolor","MyCom-border"].join(" ")}>react中的className屬性不能直接綁定數組和對象</p>

<p className={true?"MyCom-bgcolor ":""}>對於需要通過一個布爾值來控制是否擁有某個class,可以通過三目運算符</p>

頁面渲染
在這裏插入圖片描述
demo

import React, { Component } from 'react';
import "./MyCom.css";

class MyCom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            a:10,
            b:20,
            txtColor:"#ff0000"
        }

    }
    render() { 
        return (
            <div>
                <p>{this.state.a}+{this.state.b}={this.sum()}</p>

                <input type="color" value={this.state.txtColor} onChange={this.txtColorChange}></input>

                <p style={{color:this.state.txtColor,fontWeight:"bold"}}>react中的style屬性可以綁定一個對象。</p>

                {/* react中style和class綁定之後,就不能再設置其他值。 */}
                <p style={this.txtStyleObj()}>style屬性可以綁定一個對象字面量,也可以綁定一個方法調用,方法中返回style對象。</p>

                <hr/>

                {/* react中的className如果需要綁定數組,需要調用數組的join方法,然後綁定 */}
                <p className={["MyCom-bgcolor","MyCom-border"].join(" ")}>react中的className屬性不能直接綁定數組和對象</p>

                <p className={true?"MyCom-bgcolor ":""}>對於需要通過一個布爾值來控制是否擁有某個class,可以通過三目運算符</p>
                

            </div>
        );
    }

    // react中沒有類似vue的計算結果,對於複雜的計算,需要寫成一個計算方法,方法中返回計算的值,然後在模板中綁定這個方法調用。
    sum=()=>{
        return this.state.a+this.state.b;
    }

    txtColorChange=e=>{
        this.setState({txtColor:e.target.value});
    }

    txtStyleObj = e=>{
        return {
            border:"solid 1px "+this.state.txtColor,
            fontSize:"30px"
        }
    }
}

export default MyCom;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章