在打字稿中创建自己的反应路线类 [英] Create own react route class in typescript
问题描述
我发现了这个(reacttraining.com)站点,它解释了 react-路由器的一些例子.但是我无法使用打字稿类来做到这一点.我想要做的是扩展 Route 类来构建我自己的类.现在我想在打字稿中实现它以进行身份验证,如下面的网站示例所示.
I found this (reacttraining.com) site, which explains react-router with some examples. But I am not be able to do this with a typescript class. What I want to do is extend the Route class to build my own one. Right now I want to implement it in typescript for authentication as in the following example from the site.
const PrivateRoute = ({ component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
React.createElement(component, props)
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
我搜索了很多,但找不到解释要实现的函数以及调用嵌套路由的类型属性的站点.ES6 类也会有所帮助,谢谢.
I searched a lot, but couldn't find a site that explains the function to implement and which typed properties to call to nested routes. An ES6 class will be also helpful, thank you.
推荐答案
这是我目前最好的一个镜头,虽然还有一个any
:)
Here's my best shot so far, although there's still one any
remaining :)
import * as React from "react"
import {Redirect, Route, RouteComponentProps, RouteProps} from "react-router-dom"
type RouteComponent = React.StatelessComponent<RouteComponentProps<{}>> | React.ComponentClass<any>
const AUTHENTICATED = false // TODO: implement authentication logic
export const PrivateRoute: React.StatelessComponent<RouteProps> = ({component, ...rest}) => {
const renderFn = (Component?: RouteComponent) => (props: RouteProps) => {
if (!Component) {
return null
}
if (AUTHENTICATED) {
return <Component {...props} />
}
const redirectProps = {
to: {
pathname: "/auth/sign-in",
state: {from: props.location},
},
}
return <Redirect {...redirectProps} />
}
return <Route {...rest} render={renderFn(component)} />
}
这篇关于在打字稿中创建自己的反应路线类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!