react-router v4 with Typescript:如何使用`component`参数作为jsx元素

时间:2017-08-28 08:26:38

标签: reactjs typescript react-router react-router-v4

我有这个组件包裹Route的{​​{1}}组件:

react-router-dom

// AuthRoute.tsx

错误为import * as React from "react"; import { Redirect, Route } from "react-router-dom"; import { RouteProps } from "react-router"; interface Props extends RouteProps { user: any } const AuthRoute: React.SFC<Props> = ({ user, component: Component, ...rest }) => { console.log("auth route...", user); return ( <Route {...rest} render={matchedProps => ( !user || user.expired ? <Redirect to="/login"/> : <Component {...matchedProps} /> <--- error here )}/> ); };

如何呈现element type Component does not have any construct or call signatures?有或没有参数重命名。

1 个答案:

答案 0 :(得分:0)

我想如果你想用一些额外的道具渲染传递的组件,你应该使用cloneElement来达到这个目的:

var elem = React.cloneElement(component, matchedProps);

所以你的代码看起来与此类似:

return (
    <Route {...rest} render={matchedProps => (
      !user || user.expired
        ? <Redirect to="/login"/>
        : React.cloneElement(component, matchedProps) 
    )}/>
  );