React Router 在 Nested Routes 上有一个很好的教程.
而且它非常容易创建和理解。
但是,我想将路由绑定(bind)到对话框。
基本上我在 /customers
有一个客户列表我有一个 New
按钮。当它被点击时,一个表单会显示在一个对话框中。我正在使用 Material UI。我想将路线更改为 /customers/create
路线并作为该路线更改的结果显示对话框。这意味着即使用户按下 F5 并刷新页面,他们仍然会看到对话框中显示的表单。
我做不到。我创建了嵌套的 <Route />
定义:
<Routes>
<Route path='/customers' element={<Customers />}>
<Route path='create' element={<CreateCustomer />} />
</Route>
</Routes>
我还插入了一个 <Outlet />
在我的 Customers.js
:
import { Outlet } from 'react-router-dom'
const Customers = () => {
const [dialogIsShown, setDialogIsShown] = useState(false);
return <div>
<Button onClick={() => setDialogIsShown(true)}>Create</Button>
{* customer creation component is here, inside a dialog *}
<Dilog open={dialogIsShown}>
<CreateCustomer />
</Dialog>
{* other UI parts *}
<Outlet />
</div>
}
当我点击新按钮时,我使用 useNavigate
改变路线。但是没有任何反应。
我被困在这里了。
感谢任何帮助。
最佳答案
我了解到您想单击 Customer
组件中的按钮以导航到 "/customers/create"
路由并呈现 CreateCustomer
组件到 Dialog
中。如果这是正确的,那么我相信以下内容应该接近您所描述的所需行为。
import { Outlet, useNavigate } from 'react-router-dom'
const Customers = () => {
const navigate = useNavigate();
return (
<div>
... customers list ...
<Button onClick={() => navigate("create")}>Create</Button>
<Outlet />
</div>
);
}
当路由匹配并呈现元素时,默认打开对话框。
<Routes>
<Route path='/customers' element={<Customers />}>
<Route
path='create'
element={(
<Dialog open>
<CreateCustomer />
</Dialog>
)}
/>
</Route>
</Routes>
关于javascript - 如何将 react 路线绑定(bind)到显示的对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70765789/