在 JavaScript 中,this 是執行期依函式的執行環境(也就是上下文)綁定的,這正是 React 元件裡各種 this 困擾的根源。
Facebook 在更新 React 時把 ES6 的 class 加入了元件建立方式,並建議改用繼承 React.Component 的 class 來定義元件類。官方範例:
class LikeButton extends React.Component { constructor() { super(); this.state = { liked: false }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({liked: !this.state.liked}); } render() { const text = this.state.liked ? 'liked' : 'haven\'t liked'; return ( <div onClick={this.handleClick}> You {text} this. Click to toggle. </div> ); } } ReactDOM.render( <LikeButton />, document.getElementById('example') );
這段程式碼裡有大量 this。宣告 class 時我們無從得知 this 指向誰,因為那取決於上下文;等到 new 出實例、呼叫 constructor() 時,this.state 的 this 就是該實例,render() 裡的 this.state.liked 同理。
問題出在 onClick={this.handleClick}。取函式參照本身沒問題,但此時 this 的上下文已經改變了:在原本的 React.createClass 中,handleClick 會在事件觸發時自動綁定到 LikeButton 實例;到了 ES6 class 的寫法,Facebook 取消了自動綁定,於是 handleClick() 的上下文變成 div 的 backing instance,而不是它原本該有的 LikeButton 實例。
在 constructor() 裡綁一次:
this.handleClick = this.handleClick.bind(this);
這樣在該實例的任何地方使用 handleClick(),其 this 都會是 LikeButton 實例。缺點是每個方法都得在 constructor 裡手動綁一次,方法一多就很囉嗦。
也可以改成在使用處綁:
<div onClick={this.handleClick.bind(this)}> You {text} this. Click to toggle. </div>
但 render 每次執行都會產生一個新函式,這在效能敏感的元件上並不理想。
箭頭函式除了寫法簡潔,還有一個特性:把函式的 this 綁定到「定義時」所在的上下文,正好能解決這個問題。
<div onClick={() => this.handleClick()}> You {text} this. Click to toggle. </div>
這樣 this.handleClick() 的上下文就會固定在 LikeButton 實例上。箭頭函式讓 JavaScript 更接近物件導向的編程風格,也省下了 constructor 裡那一堆綁定。
一句話記住本質:this 與作用域無關,只與執行上下文有關。三種方案裡,constructor 中 bind 最明確、效能最好,適合大量方法的元件;箭頭函式最簡潔,適合少量回呼;在使用處 bind 最直觀,但要留意重複建立函式的代價。