如何关闭Modal the React方式?

时间:2017-08-20 11:14:03

标签: javascript reactjs

我有这个模态按钮,当我按下它时会出现一个模态。 如果点击 - 外部 - modal-box,我希望它被关闭,但现在无论我是在modal-box外部还是在内部点击模式关闭。如何在modal-box外面按下反应方式使模态框关闭?

https://codepen.io/anon/pen/MvVjOR



class App extends React.Component {
  constructor(){
    super()
    this.state = {
      show: false
    }
  }
  openModal() {
    this.setState( prevState => (
    {show: !prevState.show}))
  }
  closeModal() {
    this.setState({show: false})
  }
  render() {
    return (
      <div>
      <button id='button' onClick={() => this.openModal()}>the modal button</button>
        {this.state.show && <div id='modal' onClick={() => this.closeModal()}>
        <div className="modal-box">
          <h1> I'm the AWESOME modal! </h1>
        </div>
      </div>}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))
&#13;
#modal {
  display: block;
  position: fixed;
  padding-top: 50px;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background-color: rgba(0 ,0 ,0 , 0.5);
}

.modal-box {
  z-index: 50;
  margin: auto;
  width: 80%;
  height: 200px;
  background-color: white;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

class App extends React.Component {
  constructor(){
    super()
    this.state = {
      show: false
    }
  }
  openModal() {
    this.setState( prevState => (
    {show: !prevState.show}))
  }
  closeModal(e) {
    if(e.target.id === "modal") {
      this.setState({show: false})
    }
  }
  render() {
    return (
      <div>
      <button id='button' onClick={() => this.openModal()}>the modal button</button>
        {this.state.show && <div id='modal' onClick={(e) => this.closeModal(e)}>
        <div className="modal-box">
          <h1> I'm the AWESOME modal! </h1>
        </div>
      </div>}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

这是一个演示 - https://codepen.io/anon/pen/dzmpqv