“ TS2769:没有过载匹配此调用”,消耗React组件

时间:2020-03-28 19:42:24

标签: reactjs typescript

在一段时间后尝试提高React和TypeScript的性能,但是我遇到了我似乎无法解决的TypeScript错误。

ERROR in /Users/X/Projects/job-monitor-poc/src/index.tsx
[tsl] ERROR in /Users/X/Projects/job-monitor-poc/src/index.tsx(9,2)
      TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[]'.
      Type 'Element' is missing the following properties from type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[]': length, pop, push, concat, and 26 more.

版本为:

"@types/react": "^16.9.26",
"@types/react-dom": "^16.9.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"typescript": "^3.8.3",

我的组件定义为 Hello.tsx

import * as React from 'react';

export interface HelloProps {
    compiler: string;
    framework: string;
}

// Tried this, as shown at
// https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
export const Hello = (props: HelloProps) =>
    <h2>Hello from {props.compiler} and {props.framework}!</h2>;

// And this...
export const Hello: React.SFC<HelloProps> = (props: HelloProps) =>
    <h2>Hello from {props.compiler} and {props.framework}!</h2>;

// And this...
export class Hello extends React.Component<HelloProps, {}> {
    render() {
        return <h2>Hello from {this.props.compiler} and {this.props.framework}!</h2>;
    }
}

index.tsx

正在加载哪个
import * as React from 'react';
import * as ReactDom from 'react-dom';

import { Hello } from './components/Hello';

import './styles.css';

ReactDom.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementsByTagName('body')
);

我发现了一些具有类似发音错误的TypeScript问题,尤其是this one。我尝试降级到React 16.4.7,但他们的其他建议似乎涉及对@types/react的修改。

有人遇到过这个吗?任何解决方法?我在这里自己的代码中遗漏了明显的错误吗?

1 个答案:

答案 0 :(得分:2)

document.getElementsByTagName('body')返回元素的数组。因此,提取第一个元素将解决您的错误:

ReactDOM.render(
  <Hello compiler="TypeScript" framework="React" />,
  document.getElementsByTagName("body")[0]
);

或者您可以使用更经典的document.getElementsById("root")

ReactDOM.render(
  <Hello compiler="TypeScript" framework="React" />,
  document.getElementById("root")
);

这假定HTML包含一个ID为root的div:

  <body>
    <div id="root"></div>
  </body>