gpt4 book ai didi

typescript - react 路由器上的类型安全路由参数可能吗?

转载 作者:搜寻专家 更新时间:2023-10-30 20:38:25 25 4
gpt4 key购买 nike

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

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

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

最佳答案

基于 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, {}> { }

关于typescript - react 路由器上的类型安全路由参数可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com