javascript - 如何通过调用函数呈现弹出窗口?

标签 javascript reactjs dom popup dom-events

我想在 React 中渲染一个元素,只是通过调用一个函数

通常您会使用一个组件(假设是一个Popup),它从状态中获取一个 bool 值以使其显示或不显示,并使用一些回调处理程序更改它。像这样:

import React, { useState } from "react";

import Popup from "somecomponentlibrary";
import { Button } from "pathtoyourcomponents";

export const SomeComponent = () => {
    const [open, setOpen] = useState(false);

    return (
        <>
            <Button onClick={() => { setOpen(true); }}>
                this opens a modal
            </Button>
            <Popup type={"info"} open={open} timeout={1000}>
                text within modal
                <Button onClick={() => { setOpen(false); }}></Button>
            </Popup>
        </>
    );
};

我想知道是否可以像上面那样调用一些方法在屏幕上显示它,而不是像上面那样在组件中返回它:

import React from "react";

import { Button, popup } from "pathtoyourcomponents";

export const SomeComponent = () => {
    return (
        <>
            <Button onClick={() => { popup.info("text within modal", 1000); }}>
                this opens a modal
            </Button>
        </>
    );
};

如何编写 popup 函数以便以这种方式在 DOM 中呈现 Popup 组件?

最佳答案

您可以使用 ReactDOM.render在调用函数时呈现弹出窗口:

const node = document.createElement("div");
const popup = (message, {type, timeout}) => {
  document.body.appendChild(node);
  const PopupContent = () => {
    return (
      <Popup type={type} open={true} timeout={timeout}>
        {message}
        <button
          onClick={clear}
        >Close</button>
      </Popup >
    );
  };

  const clear = () => {
    ReactDOM.unmountComponentAtNode(node);
    node.remove();
  }
  
  ReactDOM.render(<PopupContent/>, node);
};

然后调用弹窗函数:

 <Button onClick={() => { popup("text within modal", {type: "info", timeout: 1000}); }}>
    this opens a modal
 </Button>

关于javascript - 如何通过调用函数呈现弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67008939/

相关文章:

javascript - ember.js 未捕获类型错误 : Object data-size has no method 'transitionTo'

javascript - 如何优化返回 bool 值的方法的 if 语句

javascript - 如果表单不完整,取消 componentWillUnmount

javascript - 访问 li ul 中的 href 元素

javascript - jQuery - 将元素数组附加到类并使其显示在 DOM 上

javascript - 使用 Javascript 引用 JSON 对象

javascript - 如何让 CKEditor 通过 CDN 运行?

JavaScript ReferenceError - 运行 npm 测试时 undefined object

javascript - 如何修复 React 中的 "TypeError: categories.map is not a function"错误

javascript - 多个电话号码编辑的逻辑