withRouter类型检查错误作为react-router的装饰器

时间:2018-10-14 09:07:31

标签: typescript react-router react-router-dom

当我使用withRouter作为组件的装饰器时,例如

@withRouter
@observer
// observer is mobx decorator
export default class UserInfo extends React.Component<any> {
  render() {
    return (
      <div>1</div>
    )
  }
}

发生类型检查错误:

(10,1): Unable to resolve signature of class decorator when called as an expression.
  Type 'ComponentClass<Pick<any, string | number | symbol>, any>' is not assignable to type 'typeof UserInfo'.    Type 'Component<Pick<any, string | number | symbol>, any, any>' is not assignable to type 'UserInfo'.      Types of property 'render' are incompatible.        Type '() => ReactNode' is not assignable to type '() => Element'.
          Type 'ReactNode' is not assignable to type 'Element'.
            Type 'undefined' is not assignable to type 'Element'.

为什么<div>1</div>的类型是Element,而不是ReactNode? 我发现render函数的定义是render(): ReactNode,为什么打字稿认为它是Element

以及如何解决此错误?

我尝试添加返回类型render()

@withRouter
@observer
export default class UserInfo extends React.Component<any> {
  render(): React.ReactNode {
    return (
      <div>1</div>
    )
  }
}

// or
@observer
class UserInfo extends React.Component<any> {
  render(): React.ReactNode {
    return (
      <div>1</div>
    )
  }
}

export default withRouter(UserInfo)

有效,但不是优雅。我想使用withRouter作为装饰器。怎么做。

0 个答案:

没有答案