0

我的应用程序顶部有一个错误边界。它可以工作,我可以将自定义组件作为后备传递给它。但是,Typescript 声称:

'Readonly<{}> & Readonly<{ children?: ReactNode; 类型上不存在属性'fallback' }>' (errorboundary.js)

然后

没有重载匹配此调用。(索引.tsx)

import { Component } from "react";

export class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}

如何解决这个问题?

请注意,我没有使用 react-error-boundary 库。本机错误边界类应该可以完成这项工作。

编辑:完整的工作代码:

interface Props {
  fallback: React.ReactNode;
}

export class ErrorBoundary extends Component<Props> {
  state = { error: null };

  static defaultProps: Props = {
    fallback: [],
  };

  static getDerivedStateFromError(error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}

4

1 回答 1

2

您应该扩展Component传递道具的类型定义,如下所示:

interface ErrorBoundaryProps {
  fallback: JSX.Element; // if fallback is a JSX.Element
}

interface ErrorBoundaryState {
  error: boolean | null;
}

export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { ... }
于 2021-02-21T18:24:52.907 回答