React es6 es2015 modal popup

后端 未结 1 551
耶瑟儿~
耶瑟儿~ 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 component
    • It can show a component
    • controls whether the is open or not
    • passes its child, , 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

    is just a "dumb" component. It does not "control" whether it is open or not. This is up to the parent . 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 (
          

    Some Modal

    ) } }

    is aware of the open/closed state and controls its child,

    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 (
          
    {/* Only show Modal when "this.state.modalOpen === true" */} {modalOpen ? : ''}
    ); } }

    0 讨论(0)
提交回复
热议问题