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"

傳遞一個沒有值的屬性,其默認值是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

自動刪除行首/末位空格,刪除空行

<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'不會被轉(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'])

限制在多個類型中

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

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

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

限定對象中 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只能用在對象中

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

自定義一個validator,異常情況 return Error 對象

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]
})

遍歷每一個元素

Default Prop Values

會不會報錯?

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賦值后進行

Refs and the DOM

The ref Callback Attribute

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

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

回調(diào)函數(shù)的參數(shù)是該 DOM element,unmounted的時候是 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 />是一個完全新的組件,舊的狀態(tài)都將清除

當根元素類型變化,毀掉舊的樹,創(chuàng)建新的樹

包含在樹里的組件會被卸載,所有狀態(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>

在末尾添加,前面的不會重新渲染

<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é)點中唯一

Context

Why Not To Use Context

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

這是一個實驗性 API,可能會在后續(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是一個空對象

Thanks!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容