2017-01-14 36 views
1

我下面的教程的Facebook和我有一個關於下面的代碼問題:React ES6語法。它是立即傳遞函數還是調用函數?

handleClick(i) { 
    const squares = this.state.squares.slice(); 
    if (calculateWinner(squares) || squares[i]) { 
     return; 
    } 

    squares[i] = this.state.xIsNext ? 'X' : 'O'; 
    this.setState({ 
     squares: squares, 
     xIsNext: !this.state.xIsNext 
    }); 
    } 

    renderSquare(i) { 
    return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />; 
    } 

某處存在Square組件,但現在不擔心了。我的問題是onClick道具上發生了什麼。什麼是右邊?它看起來像定義一個Javascript函數的ES6語法。但是我們是否將handleClick函數傳遞給它或調用它? ES5中減少了什麼?

是不是this.handleClick(i)立即調用​​函數,而不是傳遞它?

+0

你讀過[MDN約箭頭函數的文檔(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference /功能/ Arrow_functions)? –

回答

1

this.handleClick(i) < - 立即調用。

() => this.handleClick(i) < - 是一個函數。 this.handleClick只會在調用包裝函數時調用。以上可以在ES5被改寫:

(function() { this.handleClick(i) }).bind(this) 
0

不,你用這種方式創建了一個函數,但是你並沒有在那個時候調用它。通過這種方式,創建的函數的上下文與它之外(this)保持一致。通過這種方式可以在裏面叫this.handleclick,因爲這是指外界情境

箭頭功能不會創建自己的這一背景下,所以這從封閉的上下文 了原有的意義。

arrow funtion

2

如果一個函數體是一個語句,然後(用箭頭語法時),你可以忽略它周圍的{}

() => this.handleClick(i) 

等同於:

function() { this.handleClick(i); }.bind(this); 
相關問題