反应,打字稿:不正确地扩展基类“组件”
问题描述:
我试图创建一个扩展React.Component
打字稿一类,但我有此错误:反应,打字稿:不正确地扩展基类“组件”
Class 'Provider' incorrectly extends base class 'Component<{}, {}>'.
Types of property 'render' are incompatible.
Type '(props: any) => any' is not assignable to type '() => false | Element'.
下面的代码:
import * as React from "react";
export default class Provider extends React.Component {
props;
getChildContext() {
const { children, ...context } = this.props;
return context;
}
render(props) {
const { children } = props;
return children[0];
}
}
答
错误消息告诉你render()
不期望一个参数。我怀疑你应该使用this.props
?
而且你any
类型的属性props
的定义是要隐藏在基类props
属性的类型,这样编译器将无法制定出类型的children[0]
。
答
您必须在扩展React.Component时指定道具。
从docs:
import * as React from "react";
export interface HelloProps { compiler: string; framework: string; }
// 'HelloProps' describes the shape of props.
// State is never set so we use the 'undefined' type.
export class Hello extends React.Component<HelloProps, undefined> {
render() {
return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
}
}
除了这一点:使不接受的说法。 render()
是正确的。