在React中渲染一个模态

Rendering a modal in React

本文关键字:一个 模态 React      更新时间:2023-09-26

我试图在React组件上捕获一个onclick方法来创建React模态。我已经将react-overlay添加为依赖项并将其添加到我的文件中。

import Modal from 'react-overlays';

这是锚元素,

<a href="#" onClick={this.handleClick} data-id={image.id}>

这是handleclick方法,

handleClick(event) {
    event.preventDefault();
    let mediaId = event.currentTarget.attributes['data-id'].value;
    this.setState({ overlay: <Modal show={this.state.showModal} onHide={this.close} mediaId={mediaId}/> });
  }

我得到以下错误,

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.(…)

我最近遇到了这个问题,我通过创建一个modal组件来解决这个问题。

import Modal from 'react-modal'

export default class CustomModal extends React.Component {
    constructor () {
        super();
        this.openModal = this.openModal.bind(this);
        this.closeModal = this.closeModal.bind(this);
        this.state = {
            open: false
        }
    }
    openModal () { this.setState(
        {open: true});
        $(function(){
            $("#custom-modal").appendTo("body");
        });
    }
    closeModal () {
        this.setState({open: false});
    }
    componentDidMount(){
        $(function(){
            $("#custom-modal").appendTo("body");
        });
    }
    render () {
        return (
            <div>
                <button onClick={this.openModal}>My modal</button>
                <Modal id="custom-modal" isOpen={this.state.open} onRequestClose={this.closeModal}>
                     // Modal body content here
                    <button onClick={this.closeModal}>Close</button>
                </Modal>
            </div>
        );
    }
}

然后像这样使用:

import CustomModal from '../components/CustomModal'
...
<li><CustomModal/></li>

你的状态应该包含允许你渲染模态的信息,而不是模态本身。

将组件存储在状态中是非常不寻常的。

试试这个:

  1. 在你的状态中存储一个标志来指示是否应该显示模态。
  2. 设置handleClick()
  3. 标志
  4. render()中,如果设置了标志,则渲染模态。

看起来你正在导入undefined ..

还有,看看https://github.com/fckt/react-layer-stack。这是解决React中"模态问题"的通用且干净的方法。Demo - https://fckt.github.io/react-layer-stack/

如果有人仍然对此有疑问,一个现代的方法是使用React钩子构建模态。如下所示

import React from 'react';
import './modal.css';
import FontAwesome from 'react-fontawesome';
const Modal = (props) => {
  const { closeModal } = props;
  const closeicon = () => (
    <FontAwesome
    name="times"
    onClick={closeModal}
    style={{
      color: '#000000',
      padding: '10px',
      cursor: 'pointer',
      backgroundColor: 'transparent',
      border: 0,
      position: 'absolute',
      top: '0.3rem',
      right: '0.5rem',
    }}
    />
  );
  return (
    <div className="overlay">
      <div className="content">
        { closeicon() }
        {props.children}
      </div>
    </div>
  );
};

export default Modal;

css如下图

.overlay {
    position: fixed;
    display: block; 
    overflow: auto; 
    width: 100%; 
    height: 100%; 
    top: 0; 
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5); 
    z-index: 999; 
    cursor: pointer;
  }
.content {
        margin: 15% auto;
        background-color: white;
        border-radius: 0.25rem;
        width: 50vw;
        padding: 2rem;
        position: relative;
  }

所以你可以像这样使用模态组件

 const [status, setStatus] = useState(false);
//this button will trigger the modal
<button onClick={() => setStatus(true)}>Open Modal</button>

{
status && (
<Modal closeModal={() => setStatus(false)}><p>hello worls</p></Modal>
         )
}

无需担心响应性,在样式中已经处理好了。

如需进一步说明,您可以查看此链接https://dev.to/adeyemiadekore2/how-to-build-a-reusable-and-responsive-modal-in-react-from-scratch-1o0f