簡體   English   中英

使用 react-router v6 將道具傳遞給子組件

[英]Passing props to child component with react-router v6

我將 React Router v6 與單個配置文件中的所有路由一起使用,因此,使用<Outlet />來渲染子節點。 但是,當我的路由位於單獨的配置文件中時,我不知道如何根據匹配的組件傳遞適當的道具。

// route.ts
export const routes = [
  {
    path: '/*',
    element: <Parent />,
    children: [
      {
        path: 'child1',
        elements: <Child1 />, // Typescript complains: Property 'firstName' is missing in type '{}' but required in type 'IProps'
      },
      {
        path: 'child2',
        elements: <Child2 />, // Property 'lastName' is missing in type '{}' but required in type 'IProps'
      }
    ]
  }
]
// App.ts
const App = () => {
  const _routes = useRoutes(routes)
  return _routes
}
// Parent.ts
const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <h1>Parent Component</h1>
    <Outlet /> // How to pass the appropriate props?
  )
}
interface IFirstNameProps {
  firstName: string
}

interface ILastNameProps {
  lastName: string
}

export const Child1 = (props: IProps) => {
  return (
    <h2>First Name</h2>
    {props.firstName}
  )
}

export const Child2 = (props: IProps) => {
  return (
    <h2>Last Name</h2>
    {props.lastName}
  )
}

使用<Route>組件它會是這樣的:

const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <Route path='child1' element={
      <Child1 firstName={firstName} />
    } />
    <Route path='child2' element={
      <Child2 lastName={lastName} />
    } />
  )
}

如何使用routes.ts配置文件和<Outlet />實現相同的目的?

處理這種情況的最佳方法是使用outlet context

parent組件中通過Outlet傳遞上下文。

// parent.ts
const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <h1>Parent Component</h1>
    <Outlet context=[firstName, lastName]/> // How to pass the appropriate props?
  )
}

然后,在children組件中,使用useOutletContext鈎子獲取這些上下文數據。

import { useOutletContext } from "react-router-dom";
export const Child1 = () => {
  const [firstName] = useOutletContext();
  return (
    <h2>First Name</h2>
    {props.firstName}
  )
}

export const Child2 = () => {
  const [lastName] = useOutletContext();
  return (
    <h2>Last Name</h2>
    {props.lastName}
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM