【问题标题】:Passing props to <Outlet /> when nestining routes in React Router v6?在 React Router v6 中嵌套路由时将道具传递给 <Outlet />?
【发布时间】:2021-11-18 23:20:30
【问题描述】:

在嵌套路由时如何将props 传递给&lt;Outlet /&gt; 组件?

// Parrent Comp 
{
  const [format, setFormat] = useState('rgb');
  const color = [hex, rgb, rgba]
  
  // ...

  return (
    <PaletteNavBar changeFormat={setFormat}/>

      {colorId ? <ColorBoxes /> : <Outlet color={color[format]} />}

      // setFormat(hex) is called down here
    <PaletteFooter />;
  )
}

我不想通过 URL 参数传递它们。

【问题讨论】:

  • 您真正想将color 属性值传递给的Outlet 渲染是什么?请参阅below comment,了解可能使用 React Context API 将值传递给远处的子代,而无需通过所有中间组件进行钻取。
  • ColorBoxes 将呈现 20 种颜色的调色板,Outlet 将呈现具有不同深浅的单一颜色,并且需要格式以允许您使用所选格式复制颜色
  • Outlet 组件仅渲染 Route 组件。我们需要更多的上下文。你能更新并提供MCVE吗?
  • 您通过“Outlet 组件仅渲染 Route 组件。”和“React Context API”回答了我的问题。似乎我错过了理解Outlet,我应该使用 Context API 跟踪格式。谢谢。

标签: reactjs react-router react-router-dom


【解决方案1】:

Outlet 不接受任何道具,也不会将任何道具作为道具传递给它所呈现的内容。它只是组件子路由的输出。

将它们传递给 Route 渲染的组件,它是渲染到 Outlet 中的 Route。

例子:

const Layout = () => (
  <div className="super-style">
    <h1>My super awesome layout container</h1>
    <Outlet /> // <-- children routes rendered here
  </div>
);

...

<Routes>
  <Route element={<Layout />}>
    <Route // <-- rendered into Outlet of Layout
      path="..."
      element={<Component foo="bar" />} // <-- pass props to component here
    />
    ... other routes for outlet
  </Route>
</Routes>

然而,Outlet 确实 提供了一个可以通过 useOutletContext 钩子访问的 React 上下文,因为它是一种足够常见的模式,父路由可以管理一些要与之共享的状态或值子路线。

const Layout = () => (
  const [foo, setFoo] = React.useState();

  <div className="super-style">
    <h1>My super awesome layout container</h1>
    <Outlet context={[foo, setFoo]} /> // <-- pass context value
  </div>
);

...

<Routes>
  <Route element={<Layout />}>
    <Route path="..." element={<Component />} />
    ... other routes for outlet
  </Route>
</Routes>

...

import { useOutletContext } from 'react-router-dom';

const Component = () => {
  const [foo, setFoo] = useOutletContext(); // <-- access context value

  ...
};

【讨论】:

  • 但是,如果我需要传递一个基于父组件内的 Input 标签的值怎么办?我的意思是需要在父组件内部分配值?抱歉,如果我没有说清楚。
  • @Haitham6373 如果它是父组件,那么它不会正常地将它作为道具传递给它正在渲染的子组件吗?对于您要完成的工作,您是否有更具代表性的示例?听起来您正在尝试完成 React Context API 存在的一些事情,即将值传递给后代组件而不显式钻取道具。
  • 我确实更新了示例,请再检查一遍
【解决方案2】:

你最好使用出口上下文将 props 从父路由传递到嵌套路由

https://reactrouter.com/docs/en/v6/api#useoutletcontext

【讨论】:

  • 当我需要将参数从 PrivateRoute 传递给其子组件时,此上下文 API 适用于我的情况。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2021-12-28
  • 2018-05-19
相关资源
最近更新 更多