Reach Router,渲染嵌套路由组件

问题描述 投票:1回答:1

我正在React应用程序中使用Reach router(带有打字稿)。

使用嵌套路线,我陷入了如何将嵌套组件呈现为单独的(在单独视图中)组件而不是作为父组件底部的子组件的情况。

代码类似于:

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

是否有任何方法可以将嵌套路由作为单独的组件而不是作为子组件呈现。

reactjs typescript react-tsx reach-router
1个回答
0
投票

您可以尝试类似的操作,因为react-router现在正在使用渲染道具(在以前的版本中,子道具用于嵌套)。

<Route
    path="/customers"
    render={({ match: { url } }) => (
      <>
        <PDFExport path={`${url}/:id`} />
      </>
    )}
  />
© www.soinside.com 2019 - 2024. All rights reserved.