我在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
,您将在父级中获得该组件,该父级也是空组件。
请参阅“索引路由”下的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句