reactjs - 类型 '(props: RouteProps) => JSX.Element' 不能赋值给类型 'PropsWithChildren'
我正在使用 TypeScript 和 React,我想渲染一个组件,但出现了 TypeScript 错误
类型 '(props: RouteProps) => JSX.Element' 不能赋值给类型 'PropsWithChildren'。
类型 '(props: RouteProps) => JSX.Element' 中缺少属性 'component',而在类型 'RouteProps' 中这是必需的。
import React, { ReactNode, PropsWithChildren } from "react";
import { Route, Redirect } from "react-router";
export interface RouteProps {
component: FunctionComponent;
}
interface PrivateRoutesProp {
// component: PropsWithChildren<RouteProps> // not works
// also having "noImplicitAny": true, [this was mandatory]
component: PropsWithChildren<???>; //what i have to use here,object is not working
exact: boolean;
path: string;
}
const PrivateRoute = ({ component: Component, ...rest }: PrivateRoutesProp) => (
<Route
{...rest}
render={(props) => (isLoggedIn ? <Component {...props} /> : <Redirect to="/" />)}
/>
);
export default PrivateRoute;
有人能帮我脱身吗
答案#1
PropsWithChildren 只是 type PropsWithChildren<P>=P & { children?: ReactNode }; 它应该包括 Route 的 props 和自定义 props。
这是我的想法:
export interface PrivateRoutesProp {
component: FunctionComponent;
exact: boolean;
path: string;
isLogin: boolean
}
const PrivateRoute = ({ component, isLogin, ...rest }: PropsWithChildren<PrivateRoutesProp & RouteProps>) => (
<Route
{...rest}
render={(props) => (isLogin ? React.createElement(component, props) : <Redirect to="/" />)}
/>
);
