繁体   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