4个月后,我重新开始编程,因此我决定npm更新该项目,但是它破坏了我所有的无状态功能。
interface INotFoundPageContainerProps {
history: any;
}
class NotFoundPageContainer extends React.Component<INotFoundPageContainerProps, any> {
constructor(props: INotFoundPageContainerProps) {
super(props);
this.onClickHomeButton = this.onClickHomeButton.bind(this);
}
onClickHomeButton(): void {
this.props.history.push('/');
}
render() {
return (
<NotFoundPage
onClickHomeButton={this.onClickHomeButton}
/>
);
}
}
export default withRouter(NotFoundPageContainer);
错误:
TS在上述代码的最后一行给我一个错误:
TS2345: Argument of type 'typeof NotFoundPageContainer' is not assignable to parameter of type 'ComponentType<RouteComponentProps<any, StaticContext, any>>'.
Type 'typeof NotFoundPageContainer' is not assignable to type 'StatelessComponent<RouteComponentProps<any, StaticContext, any>>'.
Type 'typeof NotFoundPageContainer' provides no match for the signature '(props: RouteComponentProps<any, StaticContext, any> & { children?: ReactNode; }, context?: any): ReactElement<any>'.
答案 0 :(得分:2)
React.Component的属性类型不正确,因为您将其包装在Router HOC中。
<NotFoundPageContainer/>
包住了组件withRouter
,该组件传递了路由器特定的属性,但您没有在NotFoundPageContainer
的类型定义中反映出来。
考虑这样的事情
import { RouteComponentProps } from 'react-router-dom';
interface INotFoundPageContainerRouterProps {
history: any;
}
interface INotFoundPageContainerProps
extends RouteComponentProps<INotFoundPageContainerRouterProps> {
}
然后您就可以正确定义组件的类型了
class NotFoundPageContainer
extends React.Component<INotFoundPageContainerProps, any> { ... }