简体   繁体   English

ReactJSA Typescript 路由 JSX 元素不接受

[英]ReactJSA Typescript Route JSX Element is not accepting

Good day everyone, I am new to ReactJS/Typescript and need some tips with below behavior.大家好,我是 ReactJS/Typescript 的新手,需要一些有关以下行为的提示。 I want to restrict access to Dashboard component with below codes:我想使用以下代码限制对 Dashboard 组件的访问:

const DashBoard = () => {
    return (
        <h1> DashBoard </h1 >
    )
}
export default DashBoard;

Protecting route to DashBoard component by using in other component NavBar:通过在其他组件 NavBar 中使用来保护到 DashBoard 组件的路由:

....
<PrivateRoute path="/dashboard" component={DashBoard} exact isAuth={true} />
...

Below is PrivateRoute:下面是私有路由:

import React from "react";
import { Route, Redirect } from "react-router-dom";

interface PrivateRouteProps {
    path: string;
    exact: boolean;
    component: JSX.Element; //using component: React.FC works
    isAuth: boolean;
}
const PrivateRoute = (props: PrivateRouteProps) => {

    return props.isAuth ? (<Route path={props.path} exact={props.exact} component={props.component} />) :
        (<Redirect to="/login" />);
};
export default PrivateRoute;

However, I got below error:但是,我收到以下错误:

Type '() => Element' is missing the following properties from type 'ReactElement<any, any>': type, props, key

My questions:我的问题:

Using "component: React.FC" or "component: any" will get above error gone but is this safe as I am returning JSX.Element in all components as per https://github.com/typescript-cheatsheets/react使用“component: React.FC”或“component: any”会得到上面的错误消失但是这是安全的因为我在所有组件中返回 JSX.Element 按照https://github.com/typescript-cheatsheets/react

Thank you谢谢

Using component: React.FC is indeed the right approach. Using component: React.FC 确实是正确的做法。

This will handle your generic types, the default prop types (like children) and the return types of your components' function(as JSX elements).这将处理您的泛型类型、默认道具类型(如子项)和组件函数的返回类型(如 JSX 元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM