您好,登錄后才能下訂單哦!
在TypeScript中,我們可以使用接口來定義組件的props,并在組件定義中設(shè)置默認(rèn)props。例如:
interface MyComponentProps {
name: string;
age?: number;
}
const MyComponent: React.FC<MyComponentProps> = ({ name, age = 18 }) => {
return (
<div>
<p>{name}</p>
<p>{age}</p>
</div>
);
};
MyComponent.defaultProps = {
age: 18,
};
在這個例子中,我們定義了一個名為MyComponent
的函數(shù)組件,它接受一個name
和可選的age
作為props。我們在組件定義中設(shè)置了age
的默認(rèn)值為18
,并在組件外部通過MyComponent.defaultProps
屬性設(shè)置了默認(rèn)props。
這樣,如果在使用MyComponent
組件時沒有傳入age
props,它會使用默認(rèn)值18
。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。