typescript - 在 Auth0 中向 ProtectedRoute 的組件傳遞屬性
我正在按照這裡的指示使用 Auth0 與 react-router-dom V6,到目前為止,我能夠讓它在基本路由下正常運作。
現在我正在嘗試使它與接受 props 的組件一起工作,但我不確定如何正確傳入 props。這是 ProtectedRoute 的程式碼
import React, { ComponentType } from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';
import { Loading } from './Loading';
interface ProtectedRouteProps {
component: ComponentType,
props: any
}
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
component, props
}) => {
const Component = withAuthenticationRequired(component, {
onRedirecting: () => <Loading />,
});
return <Component {...props} />;
};
而我正在設置基本的路由組件為
<Route path="/" element={<ProtectedRoute component={Dashboard} />}/>我的 Dashboard 元素預期有一個屬性,例如類型是 string,名稱是 testProp。正確的傳遞方式應該是什麼?我已經嘗試了以下方法,但沒有一個能正確運作。
<Route path="/" element={<ProtectedRoute component={Dashboard} testProp={"test"} />}/><Route path="/" element={<ProtectedRoute component={Dashboard} props={{testProp: "test"}} />}/>有人能提供一個範例,說明如何將 props 傳遞給 ProtectedRoute,以便它可以作為通用包裝器使用嗎?我對 React 和 TypeScript 還比較陌生,無法找到正確的方法。
編輯:
使用第二種方法時,我在 TypeScript 中得到以下錯誤
(property) ProtectedRouteProps.component: React.ComponentType<{}>
Type '({ testProp }: Props) => JSX.Element' is not assignable to type 'ComponentType<{}>'.
Type '({ testProp }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
Types of parameters '__0' and 'props' are incompatible.
Property 'testProp' is missing in type '{ children?: ReactNode; }' but required in type 'Props'.ts(2322)
答案#1
很抱歉這麼晚才回應這篇文章,但我一直找不到合適的答案,不過最終還是想辦法解決了。
我沒有使用介面,但我相信你可以很容易地將它改成使用介面。我的所有路由都被送到一個 Outlet。
試試這個:在父組件中的 ProtectedRoute 定義:
const ProtectedRoute: React.FC<{ component: React.FC<{ testProp: string }>; testProp: string; }> =
({ component, testProp }) =>
{
const Component: React.FC<{ testProp: string; }> =
withAuthenticationRequired(component);
return <Component testProp={testProp} />;
};
如果你想要在不使用該屬性的路由上使用 ProtectedRoute,請將其設為可選,並在下面的子組件範例中使用非空斷言符號(!):
const ProtectedRoute: React.FC<{ component: React.FC<{ testProp?: string }>; testProp?: string; }> =
({ component, testProp }) =>
{
const Component: React.FC<{ testProp?: string; }> =
withAuthenticationRequired(component);
return <Component testProp={testProp} />;
};
路線(無論是否使用可選參數均不變):
<Route path='/' element={<ProtectedRoute component={Dashboard} testProp={testProp} />} />
儀表板:
...your stuff here
const Dashboard: React.FC<{testProp: string; }> = ({testProp}) => {
const newVal = testProp;
...your stuff here...
};
export default Dashboard;
使用可選參數
...your stuff here
const Dashboard: React.FC<{testProp?: string; }> = ({testProp}) => {
const newVal = testProp!;
...your stuff here...
};
export default Dashboard;
