在组件ES6之间反应setState

时间:2016-06-13 16:48:40

标签: javascript reactjs ecmascript-6 state

我有一个非常简单的应用程序,我试图从子组件更新父组件的状态,如下所示:

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,我无法理解原因。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:7)

this在ES6样式语法中不会自动绑定。

或者:

  1. 在构造函数中绑定如下:this.func = this.func.bind(this)
  2. 对相关函数使用箭头函数语法,如下所示:func = () => {};
  3. 更多信息:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

答案 1 :(得分:5)

使用() => lambda提供词法作用域并在方法handleStateClick()中绑定此值的正确值:

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