簡體   English   中英

typescript 作為 prop 傳遞的 svg 組件的正確類型

[英]typescript correct type for svg component passed as prop

我正在構建一個按鈕組件:

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

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

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

我正在使用react-icons庫,我應該在接口中聲明什么類型? 如果我將 svg 元素作為 startIcon 道具傳遞,它會對類型聲明產生影響嗎?

react導入和使用ReactElement

你的圖標類型是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 導入),它與上面的結果完全相似。

我來晚了,但這可能對其他人有幫助

您可以在功能組件中定義 svg 圖標的類型,例如

export interface IconProps {
  style?: StyleProp<ViewStyle>;
  fill?: string;
  width?: number;
  height?: number;
  text?: string;
  fill_1?: string;
  fill_2?: string;
  fill_3?: string;
  fill_4?: string;
}

interface ButtonProps {
startIcon?: ({ fill, width, height, style }: IconProps) => JSX.Element;
}

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


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM