2016-09-20 61 views
0

我试图让fullcalendar玩ReactJS和引导模式不错。 我想要的是每当用户选择一个日期,一个引导模式将出现与选定的日期。ReactJS通过道具设定另一个类的状态回调

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对象使用自动bind组件为你的方法

回答

2

ReactJS。但随着ES6风格组件你希望自己做,如:

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

谢谢,它现在工作。 –

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 
}