简体   繁体   English

如何为 React Router 6.4+ 路由提供动态自定义道具

[英]How to Provide Dynamic Custom Props to React Router 6.4+ Route

I'm trying to provide dynamic custom props to a React Router Route definition using the newest React Router 6.4.我正在尝试使用最新的 React Router 6.4 为 React Router Route 定义提供动态自定义道具。 I can't find any examples to showcase how I can accomplish this.我找不到任何示例来展示我如何实现这一目标。 These would be props that are provided from the parent component of the RouterProvider declaration.这些将是从RouterProvider声明的父组件提供的道具。

An example from official documentation for 6.0 - 6.3: 6.0 - 6.3官方文档中的示例:

// Ah, nice and simple API. And it's just like the <Suspense> API!
// Nothing more to learn here.
<Route path=":userId" element={<Profile />} />

// But wait, how do I pass custom props to the <Profile>
// element? Oh ya, it's just an element. Easy.
<Route path=":userId" element={<Profile animate={true} />} />

In 6.4, your route definition looks like something like:在 6.4 中,您的路由定义类似于:

// How do I provide animate state from App component to Policy component?
const router = createBrowserRouter([{ path: '/', element: <Profile animate={animate} /> }];

export function App() {
    const [animate, setAnimate] = useState(true);
    return <RouterProvider router={router} />
}

In the example you provided you are already passing an animate prop to the routed component.在您提供的示例中,您已经animate道具传递给路由组件。 RRDv6.4.0 didn't change the Route component API. RRDv6.4.0 没有改变Route组件 API。 It seems your question is really rather about passing a dynamic prop value when the route is accessed.看来您的问题实际上是在访问路由时传递动态道具值。

Move the router declaration into the App component so the animate state is in scope.router声明移动到App组件中,以便animate state 位于 scope 中。

Example:例子:

function App() {
  const [animate, setAnimate] = useState(true);

  const router = createBrowserRouter([
    { path: "/", element: <Profile animate={animate} /> } // <-- pass prop value
  ]);

  return (
    <div className="App">
      ...
      <RouterProvider router={router} />
    </div>
  );
}

编辑 how-to-provide-custom-props-to-react-router-6-4-route

Routes I am not sure but I think that you have to use Routes in App component https://reactrouter.com/en/main/components/routes路线我不确定,但我认为你必须在 App 组件中使用路线https://reactrouter.com/en/main/components/routes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM