React和TypeScript:错误地扩展了基类'组件'

时间:2017-10-05 15:33:30

标签: reactjs typescript

我尝试使用扩展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];
  }
}

2 个答案:

答案 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]的类型。