我尝试使用扩展React.Component
的TypeScript创建一个类,但我遇到此错误:
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];
}
}
答案 0 :(得分:3)
扩展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不接受参数。
render()
是对的。
答案 1 :(得分:2)
错误消息告诉您render()
并不期望参数。我怀疑你应该使用this.props
?
此外,您对类型props
的属性any
的定义将隐藏基类中props
属性的类型,以便编译器无法工作输出children[0]
的类型。