首页 > 解决方案 > custom modal does not appear react.js

问题描述

I'm trying to call this Modal, but does not appear. I tried to put the Modal into a render() but it does not work too. I used inspect element tool and it shows the div from Modal but show it "grey".

This is the Modal

import React from 'react';
import './Modal.css';
const modal = props =>(
    <div className="modal">
        <header className="modal__header">
        <h1>{props.title}</h1>
        </header>
        <section className="modal__content">
        {props.children}
        </section>  
        <section className="modal__actions">
            {props.canCancel && (<button className="btn" onClick={props.onCancel}>Cancel</button>)}
            {props.canConfirm &&(<button className="btn" onClick={props.onConfirm}>Confirm</button>)}
        </section>
    </div>
);
export default modal;

and I´m trying to call the Modal here

import React,{Component} from 'react';
import Modal from '../components/Modal/Modal.js';

import './Investments.css';

class InvestmentsPage extends Component{
    render(){
        return(            
        <React.Fragment>
            <Modal>
                <p>Modal content</p>
            </Modal>
            <div className="investment-control">
                <p>Modal</p>
                <button className="btn btnt1" >Crear </button>
            </div>
        </React.Fragment>);
    }
}

export default InvestmentsPage;

enter image description here

标签: javascriptreactjsmodal-dialog

解决方案


你的方法是错误的。我猜这里你的模态隐藏在其他一些 DOM 元素下。您应该将 ReactDOM.createPortal() 用于模式、工具提示等:

  1. 在id='root' 的现有 div 下的index.html中,使用 id='modal' 创建新的 div;
  2. 在上面列出的模态组件中,从 'react-dom' 导入 ReactDOM 并返回 ReactDOM.createPortal( your_JSX_here , document.querySelector('#modal'))

推荐阅读