【问题标题】:RouteComponentProps from react-router-dom with custom properties来自 react-router-dom 的 RouteComponentProps 和自定义属性
【发布时间】:2021-05-02 21:10:54
【问题描述】:

我有一个名为 Navbar 的组件,它使用历史记录中的位置对象,如 RouteComponentProps 中所定义。

我尝试像这样向我的组件添加自定义道具:

interface IProps{
   title?: string
}

class Navbar extends React.Component<RouteComponentProps<{}> & IProps>{

}

虽然这不会引发错误,但当我尝试这样做时:

<Navbar title="My Custom Page Title" />

Typescript 抱怨:

键入'{标题:字符串; }' 不能分配给类型 '(IntrinsicAttributes & IntrinsicClassAttributes, never> | (Pick, never> & { ...; } ), 任何, 任何>> & 只读<...> & 只读<...>) | (IntrinsicAttributes & ... 2 更多 ... & Readonly<...>)'。 属性 'title' 不存在于类型 '(IntrinsicAttributes & IntrinsicClassAttributes, never> | (Pick, never> & { ... ; }), any, any>> & Readonly<...> & Readonly<...>) | (IntrinsicAttributes & ... 还有 2 个 ... & Readonly<...>)'.ts(2322)

最初,我曾尝试过:

interface IProps extends RouteComponentProps{
   title?: string
}

但我也遇到了打字错误。

我不确定扩展或扩展 RouteComponentProps 的正确方法是什么。

【问题讨论】:

  • 当您仅使用 prop title 调用它时,typescript 不知道路由器将注入的 props,因此您会收到该错误,因为您没有提供来自RouteComponentProps 的所需道具。
  • @LindaPaiste 但如果我使用的是 RouteComponentProps 为什么这不起作用?

标签: typescript react-router-dom


【解决方案1】:

答案似乎是这样设置Router:

export default withRouter<IProps, any>(Navbar);

我不知道该放什么,因为文档说 StaticContext(用于服务器端渲染),但现在放任何作品。重点是需要在 withRouter 中定义 IProps 作为第一个参数。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2022-01-17
    • 2022-01-19
    • 2012-02-15
    • 2022-11-24
    • 2018-10-24
    • 2023-03-23
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多