React es6 es2015 modal popup

后端 未结 1 532
耶瑟儿~
耶瑟儿~ 2021-01-13 21:51

I\'m very new to React and ES6. I\'m building a small application using React and I\'m following ES6 standard. Now I need to open a modal window on a button click.

相关标签:
1条回答
  • 2021-01-13 22:36

    I've put together an example to illustrate how you might go about this, making use of the parent/child relationship and passing down a callback.

    The scenario is basically:

    • There is a parent <App /> component
    • It can show a <Modal /> component
    • <App /> controls whether the <Modal /> is open or not
    • <App /> passes its child, <Modal />, a callback to "closeModal"

    See this JSBin example for the full solution in action: http://jsbin.com/cokola/edit?js,output

    And a visual summary:

    React Modal using Callbacks

    <Modal /> is just a "dumb" component. It does not "control" whether it is open or not. This is up to the parent <App />. The parent informs it of how to close itself via passing down a callback this.props.closeModal

    class Modal extends React.Component {
      render() {
        const { closeModal } = this.props;
    
        return (
          <div className="jumbotron" style={{position: 'absolute', width: '100%', top: 0, height: 500}}>
            <h1>Some Modal</h1>
            <button 
              className="btn btn-md btn-primary" 
              onClick={closeModal}
              >Close Modal</button>
          </div>
        )
      }
    }
    

    <App /> is aware of the open/closed state and controls its child, <Modal />

    class App extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = {
          modalOpen: false
        };
      }
    
      _openModal() {
        this.setState({modalOpen: true});
      }
    
      _closeModal() {
        this.setState({modalOpen: false});
      }
    
      render() {
        const { modalOpen } = this.state;
    
        return (
          <div>
            <button 
              className="btn btn-md btn-primary" 
              onClick={this._openModal.bind(this)}
              >Open Modal</button>
    
            {/* Only show Modal when "this.state.modalOpen === true" */}
            {modalOpen 
              ? <Modal closeModal={this._closeModal.bind(this)} />
              : ''}
          </div>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题