输入“元素| undefined'不能分配给'ReactElement <any,string | ((道具:任何)

时间:2020-07-28 10:59:16

标签: javascript reactjs typescript react-native react-props

我有一个看起来像这样的组件。此版本可完美运行:

export default function StatusMessage(isAdded: boolean, errorMessage: string) {
  if (isAdded) {
    return <ResultAlert severity="success" text="User Added" />;
  } else {
    if (errorMessage !== '') {
      if (
        errorMessage.includes('email')
      ) {
        return <ResultAlert severity="error" />;
      }
      if (
        errorMessage.includes('phone number')
      ) {
        return (
          <ResultAlert severity="error" text="" />
        );
      } 
    }
  }
}

现在,我正在尝试更改导出方式。我正在尝试:

type StatusMessageProps = {
  isAdded: boolean; 
  errorMessage: string;
}

export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
  isAdded,
  errorMessage
}) => {

但是我不断收到错误消息:

Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.
  Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
    Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here

编辑:

我正在像这样使用此组件:

 const [isAdded, setIsAdded] = useState(false);

{isSubmitted && StatusMessage(isAdded, errorMessage)}

在我的收藏夹上给我一个错误

Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)

1 个答案:

答案 0 :(得分:3)

您必须忘了在组件中返回值。您是否会忘记返回null,因为void 0是React组件无法接受的结果?

export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
  isAdded,
  errorMessage
}) => {
  if (isAdded) {
    return <ResultAlert severity="success" text="User Added" />;
  } else {
    if (errorMessage !== '') {
      if (
        errorMessage.includes('email')
      ) {
        return <ResultAlert severity="error" />;
      }
      if (
        errorMessage.includes('phone number')
      ) {
        return (
          <ResultAlert severity="error" text="" />
        );
      } 
    }

    // Here where you missed
    return null;
  }
}