我按照这里的指示使用Auth0和react路由器-dom V6,到目前为止,我能够让它与基本的路由一起工作。
现在我试图使它与接受道具的组件一起工作,我不知道如何正确地传递道具。这是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"}} />}/>
请有人提供一个示例,说明如何将道具转发到ProtectedRoute,以便将其用作通用包装器。我是新的反应和类型文字,我无法找到正确的方法,这一点。
编辑:
使用第二种方法,我在类型记录中得到了以下错误
(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)发布于 2022-09-08 13:24:01
很抱歉这么晚才回复这篇文章,但我一直未能找到合适的答案,但我设法想出了答案。
我没有使用接口,但我相信您可以轻松地将其更改为使用它们。我所有的路线都被送到了一个出口。
在父组件中尝试如下: 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,请将其设置为可选的,并使用非mull断言(!)在下面的子组件示例中:
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;https://stackoverflow.com/questions/71744479
复制相似问题