在我们的react应用程序(我们使用reactstrap)中,我们有多个页面可以显示确认模式。我们不想在每页中都包含modal code。有没有办法通过调用方法以编程方式执行此操作?
我们可以直接在公共index.html中使用普通的引导程序模式,并从util方法中使用dom选择器并调用模式,但要避免这种情况。关于如何进行此操作的任何指示?
如果您想要的只是一个可以在多个页面上使用的模式(而不是在每个页面中使用一个模式,则可以将其放在通常称为App的根组件中。
import Modal from "somewhere";
function App() {
const [modal, setModal] = useState(false);
return <>
<Model isOpen={modal} />
{/* If you need to toggle modal when clicking something in PageA, you can pass the prop down like this */}
<PageA onToggleModel={()=>{setModal(!modal)}} />
<PageB />
</>;
}
import Modal from "somewhere"
不会导致最终捆绑包中的代码重复。这样做完全没问题。这是我们所做的。
警报组件:
import React, { useState } from "react";
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
const Alert = props => {
const [modal, setModal] = useState(props.open ? props.open : true);
const toggle = () => {
setModal(!modal);
if (props.cb) {
props.cb();
}
if (props.reloadPage) {
window.location.reload();
}
};
return (
<div>
<Modal isOpen={modal} toggle={toggle}>
<ModalHeader toggle={toggle}>{props.title}</ModalHeader>
<ModalBody>{props.text}</ModalBody>
<ModalFooter>
<Button color="primary" onClick={toggle}>
Ok
</Button>
</ModalFooter>
</Modal>
</div>
);
};
export default Alert;
Util.js:
import React from "react";
import ReactDOM from "react-dom";
import Alert from "./Alert";
const Util = {
alert: (message, okCb, reload) => {
ReactDOM.render(
<Alert
title="Done"
text={message}
cb={() => {
ReactDOM.unmountComponentAtNode(
document.getElementById("modalHolder")
);
if (okCb) {
okCb();
}
}}
reloadPage={reload}
/>,
document.getElementById("modalHolder")
);
}
};
export default Util;
在index.html中,我们创建了一个dom元素:
<div id="modalHolder"></div>
因此要强制调用模式,请致电:
Util.alert("Data has been saved")