1. 程式人生 > >React 學習記錄(二)

React 學習記錄(二)

p s react index tdi 運算 color dom 字母 tor

JSX語法

jsx是應React的出現而出現的,由js和xml結合而成,遇"<"解析xml,遇"{"解析js,利用js來虛擬DOM,利用虛擬DOM Diff算法可以讓用戶毫無顧及的刷新頁面。

  一、JSX註意要點

   1.組件的首字母必須用大寫,並且必須封閉,如:<Demo />或<Demo></Demo>;

   2.已經構建好的組件內部無法使用if…else…語法,所以總結下來有兩種if…else…的實現方式:

    2.1 改變組件的屬性,可以根據條件使用三元運算符;

    2.2 根據不同情況加載不同的標簽,則在構建組件的時候,通過在render方法內使用if…else…語法、調用方法的方式實現;

  

import React,{Component} from ‘react‘
class DemoIf extends Component{
  constructor(props){
    super();
    this.state={
      name:props.name
    }
  }//構造函數
  render(){
    if(this.state.name=="cheny")
    {
      return(
        <div>
          <h1>{3>8?"Hello KuGou":"Hello EveryOne"}</h1>

//三元運算符,選擇屬性
          <h2>Are you cheny?</h2>//用大的if…else…返回不同的標簽
          {this.Sex()}//在方法內if…else…返回不同的標簽
        </div>
      )
    }
  else{
    return(
      <div>
        <h1>{3>8?"Hello KuGou":"Hello EveryOne"}</h1>
        <p>Who are you?</p>

        {this.Sex()}
      </div>
    )
  }
}
Sex(){
  if(this.state.name=="cheny")
    return <h3>You are a pretty girl</h3>
  else
    return <h3>Ugly!!</h3>
  }
}

export default DemoIf

調用組件:

    render(
      <DemoIf name="cheny"></DemoIf>,
      document.getElementById(‘if_div‘)

    )

   3.已經構建好的組件內部無法使用for(…){…}語法,所以在JSX中一般定義Array,使用map(item,index)方法實現,這種情況下需要在循環出來的標簽內加上key屬性,否則react會顯示警告:

技術分享

   4.事件綁定,on後面的首字母要大寫,如:onClick,onFocus,如果在構建組件時綁定事件需要綁定到自身:onClick={this.clickHandle.bind(this)}才可以被觸發;

   5.樣式設置時,style內設置的是json串而不是字符串,類似於font-size,background-color,需改寫成fontSize,backgroundColor。

  二、組件的生命周期

   1.componentWillMount:預加載時執行,在組件被卸載重新加載之前只會被執行一次;

   2.componentDidMount:組件加載完成之後執行,ajax請求可以在方法內;

   3.componentWillReceiveProps(nextProps):在組件接收到props的時間點時調用,參數為改變了的props;

   4.shouldComponentUpdate(nextProps, nextState):該接口實際是在組件接收到了新的props或者新的state的時候會立即調用,然後通過返回值來決定是否要重新渲染當前的組件,返回true或false;

   5.componentWillUpdate:shouldComponentUpdate為true,在組件更新之前調用;

   6.componentDidUpdate:在組件更新完成調用

  

React 學習記錄(二)