【发布时间】:2021-01-31 00:31:06
【问题描述】:
我开始在 React 项目上工作,使用 react-router-dom 并且客户端需要将项目代码转换为 Typescript
我建立2个文件夹“RouteWrapper.js”和“ProviderRoutes.js”
1-“RouteWrapper.js”
import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
export default function RouteWrapper({
component: Component,
isPrivate,
...rest
}) {
const signed = false;
if (!signed && isPrivate) {
return <Redirect exact to="/signin" />;
}
if (signed && !isPrivate) {
return <Redirect to="/" />;
}
return (
<Route {...rest} component={Component} />
);
}
RouteWrapper.propTypes = {
isPrivate: PropTypes.bool,
component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
.isRequired,
};
RouteWrapper.defaultProps = {
isPrivate: false,
};
2-“ProviderRoutes.js”
import React from 'react';
import { Switch } from 'react-router-dom';
// Components
import Route from './RouteWrapper';
import Authentication from '../Layouts/Authentication/Authentication.Layout';
import ChatApplication from '../Layouts/ChatApplication/ChatApplication.Layout';
export default function ProviderRoutes() {
return (
<Switch>
<Route exact path={["/signin", "/signup", "/reset-password"]} component={Authentication} />
<Route path="/" component={ChatApplication} isPrivate />
</Switch>
)
}
【问题讨论】:
-
Typescript 是 JavaScript 的超集。所以这已经是打字稿了。您面临的问题是什么?
-
在第一个文件第 6 行和第 7 行“绑定元素‘组件’隐含地具有‘任何’类型。”和“绑定元素 'isPrivate' 隐含地具有 'any' 类型。”
-
你是要问我们如何为这段代码的每一行添加类型?
-
是的,对不起,我对这个问题感到困惑
-
这对于stackoverflow来说太宽泛了(我们可以在上面写一个博客系列)
标签: javascript reactjs typescript react-router-dom