![](/img/trans.png)
[英]How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component?
[英]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.log
和typeof
方法檢查變量的類型。
假設這個簡單的組件:
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.