ReactJS通过道具回调设置另一个类的状态

时间:2016-09-20 07:07:44

标签: javascript jquery twitter-bootstrap reactjs babeljs

我正在尝试使用ReactJS和Bootstrap模式使fullcalendar很好玩。 我想要的是每当用户选择一个日期时,将出现一个带有所选日期的引导模态。

https://jsfiddle.net/16j1se1q/1/

这是我的代码

class Application extends React.Component {
    render() {
        return (
            <FullCalendar />
        );
    }
}

class FullCalendar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {view: {showModal: false}};
    }

    handleHideModal(){
        this.setState({view: {showModal: false}})
    }

    handleShowModal(){
        this.setState({view: {showModal: true}})
    }

    render() {
        return (
            <div>
                <div is id="calendar" class="bootswatch-flatly"></div>
                {this.state.view.showModal ? <AppointmentPopup handleHideModal={this.handleHideModal}/> : null}
            </div>
        );
    }

    componentDidMount() {
        var _that = this;
        $('#calendar').fullCalendar({
            /* ... */
            dayClick: function(date, jsEvent, view) {
                /* ... */
                _that.handleShowModal();
            }
        });
    }

    componentWillUnmount() {
        $('#calendar').fullCalendar('destroy');
    }
}

class AppointmentPopup extends React.Component {
    htmlTemplate() {
        return (
            /* ... */
        )
    }

    render() {
        return this.htmlTemplate();
    }

    componentDidMount() {
        var _that = this;
        $('.appointment-modal').modal({
            show: true,
            keyboard: false,
            backdrop: 'static'
        }).on('hide.bs.modal', function(e) {
            /* ... */
        });
        $('.appointment-modal').on('hidden.bs.modal', this.props.handleHideModal);
    }
    propTypes:{
        handleHideModal: React.PropTypes.func.isRequired
    }
}


ReactDOM.render(<Application />, document.getElementById('app'));

我的完整源代码位于:http://pastebin.com/MZbVqYFZ

它工作正常,直到我点击日期然后关闭模态。 问题是由于状态view.showModal没有改变而引起的。 我收到了错误: this.setState is not a function 似乎this.props.handleHideModal被成功调用但不知何故this不是ReactJS对象

2 个答案:

答案 0 :(得分:2)

ReactJS曾经为您自动bind该方法的组件。但是对于es6样式组件,您需要自己执行以下操作:

render() {
    return (
        <div>
            <div is id="calendar" class="bootswatch-flatly"></div>
            {this.state.view.showModal ? <AppointmentPopup handleHideModal={this.handleHideModal.bind(this)}/> : null}
        </div>
    );
}

答案 1 :(得分:1)

我同意@ konoufo的建议:你需要将你的回调函数绑定到你的实例范围。有些人喜欢这样做:

class FullCalendar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {view: {showModal: false}};

        // add this line to your constructor
        this.handleHideModal = this.handleHideModal.bind(this);
    }

    // ... rest of your code
}