reactjs - 到达路由器,渲染嵌套路由组件
问题描述
我在 React 应用程序中使用Reach 路由器(带有打字稿)。
使用嵌套路由我陷入了如何将嵌套组件呈现为单独的(在单独的视图中)组件而不是作为父组件底部的子组件的问题。
代码如下:
App.tsx
--------
<Router>
<Customers path="/customers">
<PDFExport path=":id" />
</Customers>
<Users path="/users">
<PDFExport path=":id" />
</Users>
</Router>
Customers.tsx
--------------
interface IProps extends RouteComponentProps {children: any;}
const Customers: React.FC<IProps> = props => {
const[customers,setCustomers]=React.useSate(); // somehow fetch custmers
return (
<>
{customers.map(c=>(
<Button as={Link} to={`${c.id}`} />)
}
// on click the url chages to i.g. `/customers/123`
// but I do not get navigated to the PDFExport component
// but I have to render that here as child like follow
{props.childern}
// in this case I will have the content of PDFExport component at the bottom of Customers component
</>
);
}
PDFExport.tsx
-------------
interface IProps extends RouteComponentProps {
id?: string;
}
const PDFExport: React.FC<IProps> = props => {
return <div>{props.id}</div>;
// this will contain the comon form I want to use for different parents
};
我使用 PDFExport 作为嵌套的原因是我想将它重用于不同的路线,例如;/users/:id
, /customers/:id
.
有没有办法将嵌套路由呈现为单独的组件而不是子组件。
解决方案
你可以尝试这样的事情:
const Empty = ({ children }) => {
return children;
}
<Router>
<Empty path="/customers">
<Customers path="/" />
<PDFExport path=":id" />
</Empty>
<Empty path="/users">
<Users path="/" />
<PDFExport path=":id" />
</Empty>
</Router>
当您使用/
路径定义嵌套组件时,它将用作该父级的索引组件。由于我们的父级为空,因此您将显示该索引组件。导航到 后:id
,您将在父组件中获得该组件,该组件又是空组件。
请参阅索引路线下。
推荐阅读
- pytorch - PyTorch 中两个概率分布的 Jensen-Shanon Divergence
- scala - 在 Spark DataFrame 中查找重叠数据的函数
- matlab - 由凸包创建的曲面上点的值的插值
- git - 错误变基后如何恢复代码版本?
- r - 是否可以将迷你图与 gt 一起使用?
- lua - 使用“FindFirstChild”和“WaitForChild”获得 NIL
- r - 在 R 中使用 string_detect 检测到 data.frame 列中的模式太慢
- asp.net-core - 在 ASP.NET Core 中返回 odata 4 错误
- python - 旧版本的代码出现在 docker 容器中
- discord - 嵌入命令 Discord