reactjs - react-router v6 ile çocuğa bileşen olarak props iletmek


Tüm rotaların tek bir yapılandırma dosyasında olduğu React Router v6 kullanıyorum, bu nedenle çocuğu render etmek için <Outlet /> kullanıyorum. Ancak, rotalarımı ayrı bir yapılandırma dosyasında tutarken, eşleşen bileşene bağlı olarak uygun propsları nasıl geçireceğimi bilmiyorum.

// 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> bileşenini kullanarak şöyle bir şey olurdu:

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 yapılandırma dosyası ve <Outlet /> ile aynı şeyi nasıl başarabilirim?

Cevap #1

Bu durumla başa çıkmanın en iyi yolu outlet context kullanmaktır.

parent bileşeninde bağlamı Outlet üzerinden aktarın.

// 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?
  )
}

Sonra, children bileşenlerinde, bu context verilerini useOutletContext kancası kullanarak alın.

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}
  )
}

İlgili makaleler