Bootstrap modal in React.js

前端 未结 12 1360
别跟我提以往
别跟我提以往 2020-12-02 07:19

I need to open a Bootstrap Modal from clicking on a button in a Bootstrap navbar and other places (to show data for a component instance, ie. providing \"editing\" f

12条回答
  •  [愿得一人]
    2020-12-02 08:02

    Thanks to @tgrrr for a simple solution, especially when 3rd party library is not wanted (such as React-Bootstrap). However, this solution has a problem: modal container is embedded inside react component, which leads to modal-under-background issue when outside react component (or its parent element) has position style as fixed/relative/absolute. I met this problem and came up to a new solution:

    "use strict";
    
    var React = require('react');
    var ReactDOM = require('react-dom');
    
    var SampleModal = React.createClass({
      render: function() {
        return (
          

    Title

    Modal content

    ); } }); var sampleModalId = 'sample-modal-container'; var SampleApp = React.createClass({ handleShowSampleModal: function() { var modal = React.cloneElement(); var modalContainer = document.createElement('div'); modalContainer.id = sampleModalId; document.body.appendChild(modalContainer); ReactDOM.render(modal, modalContainer, function() { var modalObj = $('#'+sampleModalId+'>.modal'); modalObj.modal('show'); modalObj.on('hidden.bs.modal', this.handleHideSampleModal); }.bind(this)); }, handleHideSampleModal: function() { $('#'+sampleModalId).remove(); }, render: function(){ return ( ) } }); module.exports = SampleApp;

    The main idea is:

    1. Clone the modal element (ReactElement object).
    2. Create a div element and insert it into document body.
    3. Render the cloned modal element in the newly inserted div element.
    4. When the render is finished, show modal. Also, attach an event listener, so that when modal is hidden, the newly inserted div element will be removed.

提交回复
热议问题