gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:29:24 29 4
gpt4 key购买 nike

当我使用 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(): ReactNode , 为什么 typescript 认为它是 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作为装饰者。怎么做。

最佳答案

您可以阅读 documentation .在其中,它说:

because The class decorator is applied to the constructor of theclass and can be used to observe, modify, or replace a classdefinition., that means it is different between @withRouter ClassComponent {} and withRouter(ClassComponent)

关于typescript - withRouter 类型检查错误作为 react-router 的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801127/

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