React Advanced guides

Agenda

原文地址

  • JSX In Depth
  • Booleans, Null, and Undefined Are Ignored
  • Typechecking With PropTypes
  • Refs and the DOM
  • Context

Agenda

  • JSX In Depth
  • Booleans, Null, and Undefined Are Ignored
  • Typechecking With PropTypes
  • Refs and the DOM
  • Context

JSX In Depth

Props Default to "True"

傳遞一個(gè)沒有值的屬性圆兵,其默認(rèn)值是true

<MyTextBox autocomplete />
//is equal
<MyTextBox autocomplete={true} />


<MyTextBox autocomplete/>

console.log(this.props.autocomplete)
// true

<MyTextBox />
console.log(this.props.autocomplete)
// undefined

Spread Attributes

const Component1 = () => {
  return <Greeting firstName="Ben" lastName="Hector" />
}

const Component2 = () => {
  const props = {firstName: 'Ben', lastName: 'Hector'}
  return <Greeting {...props} />;
}

高效但是混亂

We recommend that you use this syntax sparingly.

String Literals

自動(dòng)刪除行首/末位空格坎弯,刪除空行

<div>Hello World</div>

<div>
  Hello World
</div>

<div>
  Hello
  World
</div>

<div>

  Hello World
</div>

Booleans, Null, and Undefined Are Ignored

Booleans(false & true), null, undefined都是合法值


<div />

<div></div>

<div>{false}</div>
<div>{null}</div>
<div>{true}</div>

全部 render null

const messages = []

<div>
  {messages.length &&
    <MessageList messages={messages} />
  }
</div>

number '0'不會(huì)被轉(zhuǎn)化為 false

<div>
  {messages.length > 0 &&
    <MessageList messages={messages} />
  }
</div>

確保在&&前面的是booleans

若要顯示‘false & true, null, undefined’渴逻,需轉(zhuǎn)換為 string

<div>
  My JavaScript variable is {String(myVariable)}.
</div>

Typechecking With PropTypes

我經(jīng)常使用的 PropTypes

MyComponent.propTypes = {
  optionalArray: React.PropTypes.array,
  optionalBool: React.PropTypes.bool,
  optionalFunc: React.PropTypes.func,
  optionalNumber: React.PropTypes.number,
  optionalObject: React.PropTypes.object,
  optionalString: React.PropTypes.string,
  optionalSymbol: React.PropTypes.symbol,
}

限制在枚舉的數(shù)組中

optionalEnum: React.PropTypes.oneOf(['News', 'Photos'])

限制在多個(gè)類型中

optionalUnion: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number,
    React.PropTypes.instanceOf(Message)
])

限定數(shù)組中 value 的類型

optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number)

限定對(duì)象中 value 的類型

optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number)

限定數(shù)據(jù)結(jié)構(gòu)

optionalObjectWithShape: React.PropTypes.shape({
    color: React.PropTypes.string,
    fontSize: React.PropTypes.number
})

shape只能用在對(duì)象中

optionalObjectWithShape: React.PropTypes.shape({
  colors: React.PropTypes.shape({
    backgroundColor: React.PropTypes.string.isRequired
})

自定義一個(gè)validator,異常情況 return Error 對(duì)象

customProp: (props, propName, componentName) => {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      )
    }
}

可以用箭頭函數(shù)

自定義arrayOfobjectOf

customArrayProp: React.PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
  console.log('location', location)
  //location prop
  
  console.log('propFullName', propFullName)
  //propFullName customArrayProp[0]
})

遍歷每一個(gè)元素

Default Prop Values

會(huì)不會(huì)報(bào)錯(cuò)?

class Greeting extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired
  }

  static defaultProps = {
    name: 'Stranger'
  }

  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    )
  }
}

propTypes類型檢查在defaultProps賦值后進(jìn)行

Refs and the DOM

The ref Callback Attribute

ref 屬性可以接受一個(gè)回調(diào)函數(shù)

并且在組件mounted和unmounted時(shí)立即調(diào)用

回調(diào)函數(shù)的參數(shù)是該 DOM element鲫骗,unmounted的時(shí)候是 null

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props)
    this.handleFocus = this.handleFocus.bind(this)
  }

  handleFocus() {
    this.textInput.focus()
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input }}
        />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.handleFocus}
        />
      </div>
    )
  }
}
class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.customTextInput.handleFocus()
  }

  render() {
    return (
      <CustomTextInput
        ref={(customTextInput) => { this.customTextInput = customTextInput }}
      />
    )
  }
}
class CustomTextInput extends React.Component {
  handleFocus() {
    this.textInput.focus()
  }

  render() {
    return (
      <input
        ref={(input) => { this.textInput = input}
      />
    )
  }
}


Functional components

函數(shù)式組件织阳,需要提前聲明

function CustomTextInput(props) {
  // textInput must be declared here so the ref callback can refer to it
  let textInput = null

  function handleClick() {
    textInput.focus()
  }

  return (
    <div>
      <input
        type="text"
        ref={(input) => { textInput = input; }} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  )
}

Don't Overuse Refs

Reconciliation

The Diffing Algorithm

Elements Of Different Types

<div>
  <Counter />
</div>
<span>
  <Counter />
</span>

這里的<Counter />是一個(gè)完全新的組件,舊的狀態(tài)都將清除

當(dāng)根元素類型變化填帽,毀掉舊的樹蛛淋,創(chuàng)建新的樹

包含在樹里的組件會(huì)被卸載,所有狀態(tài)清空

DOM Elements Of The Same Type

<div className="before" title="stuff" />
<div className="after" title="stuff" />

類型相同篡腌,只更新屬性

<div style={{color: 'red', fontWeight: 'bold'}} />
<div style={{color: 'green', fontWeight: 'bold'}} />

只更新 color褐荷,不更新 fontWeight

Recursing On Children

<ul>
  <li>first</li>
  <li>second</li>
</ul>
<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>

在末尾添加,前面的不會(huì)重新渲染

<ul>
  <li> first </li>
  <li> second </li>
</ul>
<ul>
  <li> third </li>
  <li> first </li>
  <li> second </li>
</ul>

更新所有<li>

[slide]
{:&.bounceIn}

Keys

<ul>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>
<ul>
  <li key="2014">Connecticut</li>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>

添加 key嘹悼,更加高效

key 只需在兄弟節(jié)點(diǎn)中唯一

Context

Why Not To Use Context

如果希望穩(wěn)定叛甫,一定不要用 context。

這是一個(gè)實(shí)驗(yàn)性 API杨伙,可能會(huì)在后續(xù)版本中移除

How To Use Context

不用 context 其监,組件結(jié)構(gòu)如下:

class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.props.color}}>
        {this.props.children}
      </button>
    )
  }
}
class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button color={this.props.color}>Delete</Button>
      </div>
    )
  }
}
class MessageList extends React.Component {
  render() {
    const color = "purple";
    const children = this.props.messages.map((message) =>
      <Message text={message.text} color={color} />
    )
    return <div>{children}</div>
  }
}

使用 context傳遞 props

class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    )
  }
}

Button.contextTypes = {
  color: React.PropTypes.string
}
class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    )
  }
}
class MessageList extends React.Component {
  getChildContext() {
    return {color: "purple"}
  }

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    )
    return <div>{children}</div>
  }
}

添加childContextTypes 和 getChildContext

如果未定義contextTypes,context是一個(gè)空對(duì)象

Thanks!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末限匣,一起剝皮案震驚了整個(gè)濱河市抖苦,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌米死,老刑警劉巖锌历,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異峦筒,居然都是意外死亡辩涝,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門勘天,熙熙樓的掌柜王于貴愁眉苦臉地迎上來怔揩,“玉大人捉邢,你說我怎么就攤上這事∩滩玻” “怎么了伏伐?”我有些...
    開封第一講書人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)晕拆。 經(jīng)常有香客問我藐翎,道長(zhǎng),這世上最難降的妖魔是什么实幕? 我笑而不...
    開封第一講書人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任吝镣,我火速辦了婚禮,結(jié)果婚禮上昆庇,老公的妹妹穿的比我還像新娘末贾。我一直安慰自己,他們只是感情好整吆,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開白布拱撵。 她就那樣靜靜地躺著,像睡著了一般表蝙。 火紅的嫁衣襯著肌膚如雪拴测。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,475評(píng)論 1 312
  • 那天府蛇,我揣著相機(jī)與錄音集索,去河邊找鬼。 笑死汇跨,一個(gè)胖子當(dāng)著我的面吹牛务荆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播扰法,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼蛹含,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼毅厚!你這毒婦竟也來了塞颁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤吸耿,失蹤者是張志新(化名)和其女友劉穎祠锣,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體咽安,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伴网,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妆棒。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片澡腾。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡沸伏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出动分,到底是詐尸還是另有隱情毅糟,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布澜公,位于F島的核電站姆另,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏坟乾。R本人自食惡果不足惜迹辐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望甚侣。 院中可真熱鬧明吩,春花似錦、人聲如沸渺绒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)宗兼。三九已至躏鱼,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間殷绍,已是汗流浹背染苛。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留主到,地道東北人茶行。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像登钥,于是被迫代替她去往敵國(guó)和親畔师。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容