【问题标题】:React Router 6 and Typescript - why doesn't it pass components through props?React Router 6 和 Typescript - 为什么它不通过 props 传递组件?
【发布时间】:2021-11-10 10:47:57
【问题描述】:

在 react router 6 中,在 javascript 中,这是可行的:

<BrowserRouter>
  <Routes>
    <Route path="/" element={<AppFrame />}>
      <Route path="product" element={<ProductView />} />
    </Route>

    <Route path="*" element={<div>Nothing here</div>} />
  </Routes>
</BrowserRouter>

它在我有 {children} 的 AppFrame 内显示 ProductView。


我试图在 Typescript 和 React Router 6 中做同样的事情,但它根本不起作用——它只是显示 AppFrame。我需要做更多的事情来添加 {children} 标记吗?

我的页面布局组件:

import React from 'react';

type Props = {
    children?: React.ReactNode
  };

  
const AppFrame = ({ children }: Props)  => {
  return (
    <div>
      AppFrame
        {children}
    </div>
  )
};

export default AppFrame;

我的演示组件:

import React from 'react';
import AppFrame from '../../Components/Layout/AppFrame';



const ProductView = ()  => {
  return (

    <div>
    Product View
    </div>
  )
};

export default ProductView;

我的路线:

<BrowserRouter>
  <Routes>
    <Route path="/" element={<AppFrame />}>
      <Route path="product" element={<ProductView />} />
    </Route>

    <Route path="*" element={<div>Nothing here</div>} />
  </Routes>
</BrowserRouter>

【问题讨论】:

  • Javascript 中的第一个示例不应该,也不应该工作。在这两个 JS/TS 中,您都需要为嵌套的 Route 渲染一个 Outlet 组件。

标签: reactjs react-router-dom


【解决方案1】:

React Router 6 需要使用新的 Outlet 组件,而不是通过 {Children}。

import React from 'react';

type Props = {
    children?: React.ReactNode
  };

  
const AppFrame = ({ children }: Props)  => {
  return (
    <div>
      AppFrame
        <Outlet />
    </div>
  )
};

export default AppFrame;

【讨论】:

    【解决方案2】:

    因为语法改变。请看https://github.com/remix-run/react-router/blob/f59ee5488bc343cf3c957b7e0cc395ef5eb572d2/docs/advanced-guides/migrating-5-to-6.md#relative-routes-and-links

    // Ah, this is nice and simple!
    <Route path=":userId" component={Profile} />
    
    // But wait, how do I pass custom props to the <Profile> element??
    // Hmm, maybe we can use a render prop in those situations?
    <Route
      path=":userId"
      render={routeProps => (
        <Profile routeProps={routeProps} animate={true} />
      )}
    />
    

    【讨论】:

    • 这不是v5代码吗?
    • 你能在实时编辑器中分享你的代码,即stackbliz
    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 2018-12-27
    • 2017-09-14
    • 2019-06-08
    • 1970-01-01
    • 2015-12-30
    • 2019-08-11
    • 2023-02-13
    相关资源
    最近更新 更多