簡體   English   中英

在組件ES6之間反應setState

[英]React setState between components 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 ,我this.setState is not a function原因。 任何幫助將非常感激!

this不是ES6樣式語法中的自動綁定。

或者:

  1. 像這樣在構造函數中綁定: this.func = this.func.bind(this)
  2. 對所討論的函數使用箭頭函數語法,如下所示: func = () => {};

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

使用() => lambda提供詞法作用域並在方法handleStateClick()綁定this的正確值:

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

暫無
暫無

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

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