reactjs - 通过反应应用程序中的方法调用显示模式
问题描述
在我们的 react 应用程序(我们使用 reactstrap)中,我们有多个页面可以显示确认模式。我们不想在每个页面中都包含模式代码。有没有办法通过调用方法以编程方式执行此操作?
我们可以直接在公共 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"
在每个页面中都执行不会导致最终包中出现重复的代码。这样做完全没问题。