簡體   English   中英

“onClick = { () => this.props.onClick() } 和 onClick = {props.onClick } 有什么區別?

[英]What is the difference between "onClick = { () => this.props.onClick() } and onClick = {props.onClick }?

我在 這里關注 React 教程

請注意以下兩個代碼片段中的“onClick”屬性。

在下面的截圖中,一個箭頭 function 被分配給它,它調用 onClick() function 在道具中傳遞給它。

  class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}

But when the class Component is converted into a functional component, the onClick attribute is assigned just the reference of the onClick function passed in props.

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

為什么會這樣? 我很困惑。

在基於 class 的組件中,道具是 class 實例本身的屬性。 因此,您可以通過this訪問它們。 在功能組件中,道具作為參數傳遞給 function。

您可以在此處閱讀基於 class 和功能組件的基礎知識。

另外,歡迎來到本站!

當您使用 ES6 class 定義組件時,常見的模式是事件處理程序成為 class 上的方法。

function原型方法:

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

and you bind the state() in constructor using this: 

constructor(props) {
    super(props);
    
    // This binding will help you to read "this." in the function
    this.onClick = this.onClick.bind(this);
  }

onClick() {
// u can read this here
}

箭頭 function 方法

另一種做同樣事情的方法是:在下面的方法中,您不必在構造函數中綁定並使用箭頭 function 代替。 在 function 里面,這個。 將有 state。

onClick = () => {
// u can read this here
}

兩者都只是兩種方法。 箭頭 function 方法和 function 原型方法

暫無
暫無

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

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