使用简单的函数从我的 React 应用程序中的任何位置调用模式或抽屉。 我已经通过使用 root.render 完成了这项工作,但是 root.render 的问题是他们无法找到我以前的任何提供程序,这使我在该组件中再次复制并导入所有提供程序。即使不使用门户,有没有办法做到这一点?
函数代码:
const handleDelete = async () => {
try {
const res = await SheetManager(".KeyDrawerGlobal", "KeyEdit");
console.log(res);
} catch (error) {
console.error(error);
}
};
这是 SheetManager 代码:
import React from "react";
import _ from "lodash";
import SheetComponent from "./SheetRegister";
import { SwipeableDrawer } from "@mui/material";
import { createPortal } from "react-dom";
const SheetManager = (container = "body", component = null, options = {}) => {
return new Promise((resolve, reject) => {
const parent = document.querySelector(container);
if (!parent) return reject();
const handleClose = (result) => {
if (result) resolve({ result });
reject();
};
createPortal(
<SwipeableDrawer
container={parent}
anchor="bottom"
open={true}
onClose={handleClose}
onOpen={() => {}}
disableSwipeToOpen={false}
ModalProps={{
keepMounted: true,
sx: {
position: "absolute !important",
},
componentsProps: {
backdrop: {
sx: {
position: "absolute !important",
},
},
},
}}
PaperProps={{
sx: {
position: "absolute !important",
borderTopLeftRadius: "16px",
borderTopRightRadius: "16px",
},
}}
>
<SheetComponent type={component} {...options} />
</SwipeableDrawer>,
document.body
);
});
};
export default SheetManager;
我通过像上下文一样使用它创建了一个解决方案,结果如下:
import {
SwipeableDrawer,
} from "@mui/material";
import React, { createContext, useState, useContext } from "react";
import { createPortal } from "react-dom";
import SheetComponent from "../components/core/sheet/SheetRegister";
const SheetContext = createContext();
export const useSheet = () => useContext(SheetContext);
let showSheet;
export const SheetProvider = ({ children }) => {
const [modal, setSheet] = useState(null);
showSheet = (container = "body", component, props) => {
const parent = document.querySelector(container);
return new Promise((resolve, reject) => {
const handleClose = (result) => {
setSheet(null);
if (result) resolve(result);
else reject();
};
setSheet({ container: parent, component, props, handleClose });
});
};
return (
<SheetContext.Provider value={showSheet}>
{children}
{modal &&
createPortal(
<SwipeableDrawer
container={modal.container}
anchor="bottom"
open={true}
onClose={() => modal.handleClose()}
onOpen={() => {}}
disableSwipeToOpen={false}
ModalProps={{
keepMounted: true,
sx: {
position: "absolute !important",
},
componentsProps: {
backdrop: {
sx: {
position: "absolute !important",
},
},
},
}}
PaperProps={{
sx: {
position: "absolute !important",
borderTopLeftRadius: "16px",
borderTopRightRadius: "16px",
},
}}
>
<SheetComponent
type={modal.component}
{...modal.props}
handleClose={modal.handleClose}
/>
</SwipeableDrawer>,
modal.container
)}
</SheetContext.Provider>
);
};
export { showSheet };