【问题标题】:typescript correct type for svg component passed as propsvg 组件的打字稿正确类型作为道具传递
【发布时间】:2021-12-09 12:29:16
【问题描述】:

我正在构建一个按钮组件:

interface ButtonProps {
   startIcon?: ... <-- what type?
}

const Button = ({startIcon: StartIcon}) => {
   return <button>{StartIcon && <StartIcon/>}</button>
}

// usage
<Button startIcon={SomeIcon}/>

我正在使用react-icons 库,我应该在接口中声明什么类型?如果我将 svg 元素作为 startIcon 属性传递,它对类型声明有影响吗?

【问题讨论】:

  • 我相信 react-icons 提供了一个 IconType 类型,可以在这里解决问题

标签: reactjs typescript svg react-icons


【解决方案1】:

你的图标类型是FunctionComponent,所以你可以简单地从react库中导入它:

import React, {FunctionComponent} from 'react';
// rest of the codes ...

interface ButtonProps {
  startIcon?: FunctionComponent 
}

可选

您可以使用简单的console.logtypeof 方法检查变量的类型。

假设这个简单的组件:

const SampleComponent = () => <p>Hello</p>

现在检查类型:

console.log(SampleComponent);
console.log(typeof SampleComponent) // function

现在,检查图标类型(从 react-icons 导入),它与上面的结果完全相似。

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 2019-09-25
    • 2021-11-10
    • 2018-06-25
    • 2022-11-28
    • 2021-06-17
    • 2019-06-20
    • 2020-03-22
    相关资源
    最近更新 更多