2016-07-16 48 views
0

我试图在react-modal内显示简单消息,具体取决于父级的状态。为了简单起见,我在Modal中有一个按钮,它可以在单击时更改父级的状态。然后,它应该在Modal上显示一条消息,但这并不会发生,直到我关闭并重新打开模式。更新反应模态内的父状态

这是代码的简化版本。该模式被重新打开后

var Modal = require('react-modal'); 

var SomeComponent = React.createClass({ 
    getInitialState: function() { 
    return { 
     showMsg: false, 
     modalOpen: false 
    } 
    }, 
    showMessage: function() { 
    this.state.showMsg = true; 
    }, 
    showModal: function() { 
    this.state.modalOpen = true; 
    } 

    render: function() { 
    return (
     <div> 
     <button onClick={this.showModal}>Show modal</button> 
     <Modal isOpen={this.state.modalOpen}> 
      <button onClick={this.showMessage}>Show message</button> 
      { 
      this.state.showMsg ? 
       "This is the message" 
      : 
       null 
      } 
     </Modal> 
     </div> 
    ) 
    } 
}); 

This is the message将只显示,但我想让它显示,而它的开放。

+2

不要使用'this.state.modalOpen'变换状态对象等。总是使用'this.setState()'函数 –

回答

0

为了使您的模态即使在您的模态打开时也能显示消息,请使用 this.setState()来设置状态。它会改变你的状态并触发反应组件的重新渲染。

var Modal = require('react-modal'); 

var SomeComponent = React.createClass({ 
    getInitialState: function() { 
    return { 
     showMsg: false, 
     modalOpen: false 
    } 
    }, 
    showMessage: function() { 
    this.setState({showMsg: true}); 
    }, 
    showModal: function() { 
    this.setState({modalOpen: true}); 
    } 

    render: function() { 
    return (
     <div> 
     <button onClick={this.showModal}>Show modal</button> 
     <Modal isOpen={this.state.modalOpen}> 
      <button onClick={this.showMessage}>Show message</button> 
      { 
      this.state.showMsg ? 
       "This is the message" 
      : 
       null 
      } 
     </Modal> 
     </div> 
    ) 
    } 
});