【问题标题】:Reach Router, render nested route component到达路由器,渲染嵌套路由组件
【发布时间】:2019-10-22 13:41:00
【问题描述】:

我在 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】:

    你可以试试这样的:

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

    请看Index Routes下方。

    【讨论】:

    • 这不是 react-router,是REACH ROUTER
    • 谢谢,它工作,虽然引入一个空组件有点连线,但我在项目的中间,没有其他办法:)
    • 我同意,也许用更好的措辞看起来会更好看,也许像“占位符”。
    • 是的,措辞,在早期阶段,我可以有一些功能,比如wrapperplaceholder,比如所有孩子都需要的一些界面或功能,这样看起来更专业、更快乐项目经理:D
    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2018-11-26
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多