簡體   English   中英

在課堂上綁定構造函數或胖箭頭

[英]Bind in constructor or fat arrow in class

所以我想知道這是否有區別:

import React, { Component, PropTypes } from 'react';

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page : 1
    };
  }

  nextPage = () => {
    this.setState({ page: this.state.page + 1 });
  }

  previousPage= () => {
    this.setState({ page: this.state.page - 1 });
  }

  render() {
    const { page } = this.state;
    return (
      <div>
        <H1>{page}</H1>
        <Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
      </div>
    );
  }
}

要么

import React, { Component, PropTypes } from 'react';

class Example extends Component {   
    constructor(props) {
         super(props);
         this.nextPage = this.nextPage.bind(this);
         this.previousPage = this.previousPage.bind(this);
         this.state = {
              page: 1
             };
  }

  nextPage() {
    this.setState({ page: this.state.page + 1 });   }

  previousPage() {
    this.setState({ page: this.state.page - 1 });   }

  render() {
    const { page } = this.state;
    return (
      <div>
        <H1>{page}</H1>
        <Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
      </div>
    );   
  }
}

我想知道每個功能的性能是否相同,還是有任何其他好處?

進一步閱讀( https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.khf30fuaq

綁定事件處理程序的最佳位置是constructor 這樣,您的事件處理程序將其上下文綁定到組件實例。您可以訪問props and state並從此綁定處理程序中調用setStateforceUpdate

arrow功能綁定也有其自身的優點。 箭頭函數始終從定義它們的位置獲取上下文。 所以實際上,這個例子相當於:

箭頭函數語法是一種使用如下語法定義函數的方法:

change = (ev) => this.setState({ text: ev.target.value });

它比編寫function(ev) { .... }語句更簡潔。 如果在=>箭頭后沒有提供{}括號,則此函數是一個立即返回的表達式。 所以這就像以下一樣:

change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);

因此.bind()arrow函數都會導致創建一個新函數

總而言之,您希望綁定函數的方式取決於您的用例。

欲了解更多詳細信息,你可以閱讀了文章:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM