【问题标题】:Type safety on react-router Route params possible?react-router Route参数上的类型安全可能吗?
【发布时间】:2016-06-18 07:17:08
【问题描述】:

是否可以安全地使用 TypeScript 访问 react-router 2.0 路由属性?例如:

<Router>
  <Route path="/" component={App}>
    <Route path="screenOne" header="Screen One" component={ScreenOne}/>
  </Route>
</Router>

screenOne Route 的标头值可以通过“this.props.route.header”访问,但似乎不可能同时设置它并使用 TypeScript 访问它而不收到该属性不存在的警告在 Route 侧或访问该属性的组件内部。我查看了http://definitelytyped.org/https://github.com/typings/typings 中的定义文件

【问题讨论】:

  • 你可以尝试扩展RouteRouteProps

标签: typescript react-router


【解决方案1】:

根据https://stackoverflow.com/users/2225281/aaron 的评论,您似乎可以这样做,但使用 Typings 中的定义有点愚蠢。也许有人可以对此进行扩展以进行改进或有更好的主意,但这是我迄今为止在 routes.tsx 文件或类似文件中所假设的:

//Create a type to limit duplication and help w/refactoring
type Header = string;

//Interface for the injected props. Used by component via 'this.props.route.header'
export interface HeaderRouteInjectedProps extends IInjectedProps {
  route?: IRoute & {
    header: Header
  }
}

//Interface and class to create a new Route type 'HeaderRoute' that requires a header property
interface HeaderRouteProps extends IRouteProps {
  header: Header
}
class HeaderRoute extends React.Component<HeaderRouteProps, {}> { }

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2020-06-03
    • 2018-10-25
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多