[英]How to define a component with default value
這是我的組件( Amount.tsx
):
export const Amount = ({price, prevPrice}) => {
return (
<div className="product-amount">
<div className="price">
{prevPrice ? (<del className="prev">{Number(prevPrice).toLocaleString()} تومان </del>) : ''}
<ins className="current">{${Number(price).toLocaleString()} تومان }</ins>
</div>
</div>
)
}
我想在沒有默認值的情況下調用這個組件。 例如:
return (
<Amount />
)
您可以通過使用解構默認值來做到這一點:
export const Amount = ({price = defaultForPrice, prevPrice = defaultForPrevPrice} = {}) => {
// #1 −−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^
// ...
};
對於普通的 function,您還需要為整個參數提供一個默認值(在解構的關閉}
之后添加= {}
),但不使用組件 function,因為它們總是傳遞一個道具object(即使是空的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.