在 React Router v6 中嵌套路由时将 props 传递给 <Outlet />?

Hai*_*373 7 reactjs react-router react-router-dom

当我嵌套路由时,如何传递props给组件?<Outlet />

// Parent 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 />;
  )
}
Run Code Online (Sandbox Code Playgroud)

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

Dre*_*ese 15

Outlet接受任何 props,也不会将任何东西作为 props 传递给它所渲染的内容。它只是组件子路由的输出。

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

例子:

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

...

<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>
Run Code Online (Sandbox Code Playgroud)

然而,它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>
);
Run Code Online (Sandbox Code Playgroud)

...

<Routes>
  <Route element={<Layout />}>
    <Route path="..." element={<Component />} />
    ... other routes for outlet
  </Route>
</Routes>
Run Code Online (Sandbox Code Playgroud)

...

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

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

  ...
};
Run Code Online (Sandbox Code Playgroud)