React Native 函數(shù)的綁定

在ES6的class中函數(shù)不再被自動(dòng)綁定,你需要手動(dòng)去綁定它們。

第一種在構(gòu)造函數(shù)里綁定。

  constructor(props) {
    super(props); 
    // Set up initial state
    this.state = {
        text: props.initialValue || 'placeholder' 
};
    // Functions must be bound manually with ES6 classes
    this.handleChange = this.handleChange.bind(this); 

另一種方式就是在你使用的地方通過(guò)內(nèi)聯(lián)來(lái)綁定:

// Use `.bind`:
 render() { 
    return (
     <input onChange={this.handleChange.bind(this)}
     value={this.state.text} /> 
);
}
// Use an arrow function:
render() {
     return (
        <input onChange={() =>  this.handleChange()} 
    value={this.state.text} />
);

以上任意一種都可以,然而在效率上卻不行了。每一次調(diào)用render(可以說(shuō)是非常頻繁!)一個(gè)新的函數(shù)都會(huì)被創(chuàng)建。與在構(gòu)造函數(shù)里只綁定一次相比就慢一些。

最終的選擇是使用箭頭函數(shù)直接替換函數(shù)在類(lèi)中的聲明,像這樣:

// the normal way
// requires binding elsewhere
handleChange(event) {
    this.setState({
    text: event.target.value
    });
}
// the ES7 way
// all done, no binding required
handleChange = (event) => { 
  this.setState({
text: event.target.value
  });
}

通過(guò)這種方式,你不需要綁定任何東西。這都已經(jīng)通過(guò)神奇的箭頭函數(shù)被搞定了。像期望的那樣,函數(shù)內(nèi)部的this將會(huì)指向組件實(shí)例。參考:http://www.lxweimin.com/p/a4c23654932e

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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