如何访问和声明 React 组件的类型?

问题描述

这里我有一个组件应该打印一个 toast,根据 toast 的类型向内容添加一个图标:

import * as React from 'react';
import { toast }  from 'react-toastify';
import { FaInfo,FaCheck,FaExclamationTriangle,FaBug,FaExclamationCircle } from 'react-icons/fa';
import { TypeOptions,ToastContent,Toast } from 'react-toastify/dist/types/index';

interface IToast {
  message: ToastContent;
  type: TypeOptions;
}
    
const displayIcon = ({ type }: IToast) => {
          switch (type) {
            case 'success':
              return <FaCheck />;
            case 'info':
              return <FaInfo />;
            case 'error':
              return <FaExclamationCircle />;
            case 'warning':
              return <FaExclamationTriangle />;
            default:
              return <FaBug />;
          }
        };
    
const myToast = ({ type,message }: IToast): Toast => {
  return toast[type](
    <div>
      <div>
        {displayIcon(type)}
      </div>
      <div>{message}</div>
    </div>,);
};

export default myToast;

我正在通过以下方式在另一个组件上渲染 myToast:

const notify = React.useCallback((message: ToastContent,type: ToastOptions) => {
lomplayToast({ message,type });
  },[]);

这些组件已经可以工作,并且可以按预期执行。但我无法做出好的类型声明。 Toast 接口带有多个接口和类型声明。其中之一是 displayIcon 能够检索的 ToastOptions 类型。我的问题:

  1. 为什么 toast[type] 属性会抛出“属性 'default' 在类型 '{ 上不存在(消息:ToastContent,类型:TypeOptions | 未定义):ReactText;...”?这个属性来自哪里?

解决方法

有两个地方可以在函数上声明类型。

  1. 您可以为 props 声明类型。
  2. 您可以为函数返回的内容声明一个类型,即 ReturnType

看起来像这样

const yourFunction = (props: PropType): ReturnType => { ... }

您将 ToastProps 声明为 ReturnType

这样做:

const myToast = ({ type,message }: ToastProps) => { ... }

代替:

const myToast = ({ type,message }): ToastProps => { ... }

这是一个非常微妙的变化。


注意:这对任何函数都很重要,但 React 有自己的函数类型。你可以像这样输入一个 React 组件函数:

const myToast: React.FunctionComponent<ToastProps> = ({ message,type }) => { ... }

在幕后,它会创建这样的东西:

const myToast = (props: ToastProps): JSX.Element => { ... }
// It does some more stuff,but I simplified it for this example.