Typography

活版印字


  • Home
  • Archive
  • Categories
  • Tags
  •  

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo

React Bind

Posted at 2016-05-14 React 

React on ES6 不再 自動綁定,這是在很多網路文章都會提到的事,但總是覺得矇矇懂,今天看到一個範例終於比較有感了。

就是在之前 handleOptionsButtonClick 內的 this 不需要綁定,就會預設為 this 是一個 component instance,但是在 ES6 的寫法,你需要加 this.handleOptionsButtonClick.bind(this),它才會將 handleOptionsButtonClick 內的 this 視為是 component instance,否則無法使用 component instance 的 method。

範例一

1
2
3
4
5
6
7
8
9
10
11
class PostInfo extends React.Component {
constructor(props) {
super(props);
// 手動綁定,這裡的 this 指的是 component instance
this.handleOptionsButtonClick = this.handleOptionsButtonClick.bind(this);
}
handleOptionsButtonClick(e) {
// 被 bind 之後,這裡的 this 將指的是 component instance。
this.setState({showOptionsModal: true});
}
}

範例二

1
2
3
4
5
6
7
8
9
10
_checkShopCode() {
// … 略...
}

_changeDeliverZone(e) {
CartActions.changeDeliverZone(e.target.value);
this._updateCartSum();
}

<select style={styles.select} value={this.props.selectedDeliverZone} onChange={this._changeDeliverZone.bind(this)}>

Share 

 Previous post: 有效的時間管理 - 重點整理(1) Next post: CDNJS - JavaScript CDN 

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo