React組件-組件編寫

編寫組件

頁面結構html

組件react


注意:json

  • 組件必須繼承React.Component
  • 組件必須有constructor()且super父級,不然狀態等功能沒法使用
  • 組件必須有render()方法
  • 組件名(類名)必須首字母大寫
  • 組件使用時,單雙標籤均可以
  • 組件中的HTML必須規範(雙標籤閉合,單標籤結尾加/)

模板輸出數組

輸出變量,屬性,方法...任何東西均可以bash

class Cmp1 extends React.Component{ 
    constructor(...args){
        super(...args);
        this.age=18
    }
    fn(){
        return 55
    }
    render (){
        let name='張三';
        return <div>
            //輸出變量
            姓名:{name}<br/>
            //輸出屬性
            年齡:{this.age}<br/>
            {this.fn()}
        </div>
    }}複製代碼

輸出到屬性ui

class Cmp1 extends React.Component{
    contructor(...args){
        super(...args);
    }
    render(){
        let a=12;
        return <div>
            <!-- 輸出字符串」a「 -->
            <div title="a">box1</div>

            <!-- 輸出變量 -->
            <div title={a}>box2</div>
        </div>;
    }
}
複製代碼

組件傳參this

props接受參數spa

class Cmp1 extends.Component{
    constructor(...args){
        super(..args)
    }
    render(){
        return{
            <div>
                {this.props.a},{typeof(this.props.a)}
            </div>
        };
    }
}
//方法1.字符串
//<Com1 a="12"/>
//12,string

//方法2.其餘類型(數組,數字,json等)
//<Cmp1 a={12}/}
//12,number

//<Cmp1 a={{name:'blue'}}/>
//{name:blue,object}

複製代碼

注意:若是但願給組件傳遞參數(數字,json等),必須使用{},不然傳遞的都是字符串3d

html組件的stylecode

render(){
    return{
        //錯誤
        <div style="width:200px;height:200px"></div>
        //正確
        <div style={{width:'200px',height:'200px'}}></div>
    }
}
複製代碼

注意:react中不存在{{}}寫法,外面一層{}是react的表達式,裏面一層{}是json的一部分

html組件的class

render(){
    return{
        <div className=「box1」>
            組件類名
        </div>
    }
}複製代碼
相關文章
相關標籤/搜索