【问题标题】:How do you access and declare the types of a react component?你如何访问和声明一个 React 组件的类型?
【发布时间】:2021-04-26 13:31:06
【问题描述】:

这里我有一个组件应该打印一个 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] 属性会抛出“类型'{ 上不存在属性'默认'(消息:ToastContent,类型:TypeOptions | undefined):ReactText;...”?这个默认属性是从哪里来的?

【问题讨论】:

    标签: typescript interface react-toastify


    【解决方案1】:

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

    1. 您可以为道具声明类型。
    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.
    

    【讨论】:

    • 非常感谢!那么如何编辑外部组件的回调函数来设置 const myToast 的值?我已经按照建议更改了类型,它确实可以正确推断类型,但外部组件显示 An argument matching this binding pattern was not provided.
    • 啊,我明白了,您的 myToast 函数实际上不是 React 组件。它被用作回调,而不是组件。我的错,我误读了你的代码。你可以忽略我回答的最后一部分。只需像这样声明您的 myToast 函数:const myToast = ({ type, message }: ToastProps) =&gt; { ... } 就可以了。
    猜你喜欢
    • 2020-10-24
    • 2015-10-23
    • 1970-01-01
    • 2018-04-04
    • 2017-07-19
    • 2020-09-19
    • 1970-01-01
    • 2019-11-21
    • 2018-10-04
    相关资源
    最近更新 更多