首页 > 解决方案 > 到达路由器,渲染嵌套路由组件

问题描述

我在 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.

有没有办法将嵌套路由呈现为单独的组件而不是子组件。

标签: reactjstypescriptreact-tsxreach-router

解决方案


你可以尝试这样的事情:

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,您将在父组件中获得该组件,该组件又是空组件。

请参阅索引路线下。


推荐阅读