簡體   English   中英

如何為功能性React組件建立默認道具

[英]How do I establish default props for functional React components

定義功能性React組件的默認prop值的正確方法是什么?

使用TypeScript

interface ThingProps {
    something?: number;
}

const Thing: FC<ThingProps> = (props: ThingProps): ReactElement => {
    const something = props.something || 0    
    // ...
}

讓我寫

<Thing />

要么

<Thing something={someValue} />

兩者都可以正常工作。

這是正確的習慣用法,還是React有不同的首選方式來實現這一目標?


請注意,盡管這里有一些答案 ,但它們已經很老了(2016年),對我沒有任何幫助:它們會因<Thing /> (缺少必需的屬性)或使用something (可能不確定)而導致TS錯誤。

您可以直接在Thing上設置它們:

Thing.defaultProps = {
  something: 0
};

您可以在函數聲明中簡單地將props參數分配給默認值(或帶有值的對象):

interface ThingProps {
  something?: number;
}

const Thing: React.FC<ThingProps> = (props = {something: 1337}) => {
  return <>{props.something}</>
}

或使用我個人覺得更干凈的點差運算符:

interface ThingProps {
  something?: number;
}

const Thing: React.FC<ThingProps> = ({something = 1337}) => {
  return <>{something}</>
}

如果您不需要在其他地方重用ThingProps接口,您甚至可以內聯進行所有操作:

const Thing: React.FC<{ something?: number; }> = ({something = 1337}) => {
  return <>{something}</>
}

順便說一句我很確定

const Thing: FC<ThingProps> = (props: ThingProps): ReactElement => {

多余的vs只是做的

const Thing: FC<ThingProps> = (props) => {

因為您已經在變量聲明ThingProps Thing鍵入為React功能組件,並將props鍵入為ThingProps

暫無
暫無

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

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