2016-06-13 87 views
2

我有,我想從一個子組件更新父組件的狀態如下一個非常簡單的應用:反應的組分之間的setState ES6

import React from '../../../../../../../dependencies/node_modules/react'; 
import ReactDOM from '../../../../../../../dependencies/node_modules/react-dom'; 

class CalendarMain extends React.Component { 
    constructor() { 
     super(); 
    } 

    handleClick() { 
     this.props.handleStateClick("State Changed"); 
    } 

    render() { 
     return ( 
      <div> 
       <div className="calendar"> 
        {this.props.checkIn} 
        <button onClick={ this.handleClick.bind(this) }>Click Me</button> 
       </div> 
      </div> 
     ) 
    } 
} 

class CalendarApp extends React.Component { 

    constructor() { 
     super(); 

     this.state = { 
      checkIn: "Check-in", 
      checkOut: "Check-out", 
      dateSelected: false 
     }; 
    } 

    handleStateClick(newState) { 
     this.setState({ 
      checkIn: newState 
     }); 
    } 

    render() { 

     return (
      <div> 
       <CalendarMain 
        checkIn = { this.state.checkIn } 
        handleStateClick = { this.handleStateClick.bind(this) } 
       /> 
      </div> 
     ); 
    } 
} 

我收到的錯誤是this.setState is not a function可以和我沒有解決原因。任何幫助將非常感激!

+1

確保你不會在別處意外地突變'this.setState'。即:'this.setState = {foo:'bar'};' – Kujira

+0

只需注意'../../ ..'...確保相對路徑保持在您的項目中,否則移動項目(上傳到遠程,在github上發佈/ npm,無論如何)都可能破壞這些路徑。 –

+1

您可能想重新考慮您的項目層次結構 –

回答

7

this未在ES6樣式語法中自動綁定。

或者:

  1. 綁定在構造函數中,像這樣:func =() => {};

這裏更多:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

+0

[MDN文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)上的箭頭函數(lambdas)以供參考 –

+0

OP似乎已經將其綁定了:'handleStateClick = {this.handleStateClick.bind(this)}'。 –

5

使用this.func = this.func.bind(this)

  • 有問題的功能,像這樣使用方向函數的語法() => lambda提供詞法範圍並在方法內綁定正確的值:

    handleStateClick =() => { 
        this.setState({ 
        checkIn: newState 
        }); 
    } 
    
  • +0

    您可能想要解釋此功能是實驗性功能,以及Babel轉換爲包含此功能的功能。 –

    +1

    假設OP已經在使用ES6類和導入,人們會認爲它們具有所有必備環境設置 –

    +0

    似乎有點延伸......您是否知道這是一個提議而不是ES6的一部分? –