如何通过React Router v6的包装组件传递任意数量的props
React ProtectedRoute 传递Props的类型错误解决方法
错误原因分析
第一种传递方式错误
element: <ProtectedRoute component={ProjectBoard} prop1={prop1} prop2={prop2}/>
错误信息:Type '({ prop1, prop2 }: Props) => JSX.Element' is not assignable to type 'ComponentType<{}>'
根源是你定义的ProtectedRouteProps中component类型为ComponentType<{}>,这代表不需要任何props的组件,但ProjectBoard明确需要prop1和prop2,类型不兼容导致报错。
第二种传递方式错误
element: <ProtectedRoute component={<ProjectBoard prop1={prop1} prop2={prop2}></ProjectBoard>}/>
错误信息:Type 'Element' is not assignable to type 'ComponentType<{}>'component属性要求传入组件类型(函数/类组件本身),但你传入的是已经渲染完成的Element(<ProjectBoard />的执行结果),类型不匹配导致报错。
解决方案
方案一:泛型支持组件Props(类型安全)
修改ProtectedRoute.tsx的类型定义,通过泛型接收目标组件的Props类型,明确传递规则:
import { ComponentType } from 'react'; import { withAuthenticationRequired } from '@auth0/auth0-react'; // 泛型T接收目标组件的Props类型 interface ProtectedRouteProps<T = {}> { component: ComponentType<T>; props: T; } export const ProtectedRoute = <T extends {}>({ component: TargetComponent, props, }: ProtectedRouteProps<T>) => { const ProtectedComponent = withAuthenticationRequired(TargetComponent, { onRedirecting: () => <div>认证跳转中...</div>, }); return <ProtectedComponent {...props} />; };
在app.tsx中使用:
// 先明确组件的Props类型 interface MyComponentProps { age: number; } const MyComponent = ({ age }: MyComponentProps) => { return <p>年龄:{age}</p>; }; const router = createBrowserRouter([ { path: '/myComponent', element: <ProtectedRoute component={MyComponent} props={{ age: someState }} />, }, ]);
方案二:使用Children传递(更灵活)
调整ProtectedRoute为基于Children的模式,直接接收已携带Props的组件,无需处理类型映射:
import { ReactNode } from 'react'; import { withAuthenticationRequired } from '@auth0/auth0-react'; interface ProtectedRouteProps { children: ReactNode; } export const ProtectedRoute = ({ children }: ProtectedRouteProps) => { // 将子组件包装为需要认证的组件 const ProtectedChild = withAuthenticationRequired(() => children, { onRedirecting: () => <div>认证跳转中...</div>, }); return <ProtectedChild />; };
在app.tsx中使用:
const router = createBrowserRouter([ { path: '/myComponent', element: ( <ProtectedRoute> <MyComponent age={someState} /> </ProtectedRoute> ), }, ]);
这种方式无需额外处理类型,直接传递带Props的组件即可,适合大多数场景。
内容的提问来源于stack exchange,提问作者Jash1395
相关产品推荐
相关产品推荐

