将属性添加到StatelessComponent

时间:2018-05-17 21:07:58

标签: reactjs typescript react-router

如何为无状态组件添加属性?

例如,PrivateRoute是一个无状态组件,用于在未对用户进行身份验证时禁止导航到某些路由。 路由通过路由器访问:

import { BrowserRouter as Router, Link, Route, Redirect } from 'react-router-dom';
...
            <Router basename={baseUrl} >
            <div>
                <ul>
                    <li><Link to='/public'>Public</Link></li>
                    <li><Link to='/protected'>Protected</Link></li>
                </ul>

                <PrivateRoute path='/protected' component={Protected} auth={true}/>
            </div>
        </Router>

我的目标是传递auth = {true}(这最终将成为基于登录页面更新的标志),但是,我收到以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error   TS2339  (TS) Property 'auth' does not exist on type 'IntrinsicAttributes & RouteProps & { children?: ReactNode; }'.

PrivateRoute定义如下:

import * as React from "react"
import { Redirect, Route, RouteComponentProps, RouteProps } from "react-router-dom"

type RouteComponent = React.StatelessComponent<RouteComponentProps<{}>> | React.ComponentClass<any>
const AUTHENTICATED = true;
export const PrivateRoute: React.StatelessComponent<RouteProps> = ({ component,  ...rest }: any) => {
    const renderFn = (Component?: RouteComponent) => (props: RouteProps) => {
        if (!Component) { return null }
        console.log(props)
        if (AUTHENTICATED) { return <Component {...props} /> }

        const redirectProps = {
            to: {
                pathname: "/login",
                state: { from: props.location },
            },
        }

        return <Redirect {...redirectProps} />
    }

    return <Route {...rest} render={renderFn(component)} />
}

我试过了:

export const PrivateRoute: React.StatelessComponent<RouteProps> = ({ component, auth,  ...rest }: any) => {
    const renderFn = (Component?: RouteComponent) => (props: RouteProps) => {

以及

export const PrivateRoute: React.StatelessComponent<RouteProps> = ({ component,  ...rest }: any, auth: boolean) => {
    const renderFn = (Component?: RouteComponent) => (props: RouteProps) => {

export const PrivateRoute: React.StatelessComponent<RouteProps> = ({ component,  ...rest }: any) => {
    const renderFn = (Component?: RouteComponent, auth: boolean) => (props: RouteProps) => {

最后,我尝试通过变量发送值:

let authenticated = false
<PrivateRoute path='/protected' component={Protected} {...authenticated}/>

这样做时,我无法在道具,休息或组件中找到它。

1 个答案:

答案 0 :(得分:0)

这是一个打字稿错误,而不是反应错误。假设auth是您的自定义属性,您需要执行以下操作才能使其正常工作:

interface PrivateRouteProps extends RouteProps {
  auth?: boolean;
}
export const PrivateRoute: React.StatelessComponent<PrivateRouteProps> = ({component, auth, ...rest})

执行SFC<RouteProps & { auth?: boolean }>也应该有效。关键是你不能在React TSX中添加道具而不声明propsany或声明其他道具的类型。我不相信有一种方法可以让tsconfig.json完全跳过这个检查,但可能有办法。