[英]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>
);
}
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.