reactjs - Cum să folosești enum ca props în React/TypeScript


Am următorul enum

export enum Sizes{
    Small,
    Large
}

care este folosit în interfața de props a componentului meu <Demo/>:

export interface IProps{
    Label?: string;
    Size: SizeEnum;
}

Întrebarea mea este, când folosesc acest <Demo Size={cum definesc dimensiunea aici?} />?

Răspuns #1

Poți să te referi la valoarea enum așa cum ai face în orice alt context:

export enum Sizes{
    Small,
    Large
}

export interface IProps{
    Label?: string;
    Size: Sizes;
}

class Demo extends React.Component<IProps> {}

let d = <Demo Size={Sizes.Large} />

Răspunsul #2

Folosește type sau as const

Atât type, cât și as const au completare automată și vor afișa o eroare atunci când este folosită o valoare nevalidă.

tip

'up'   

Implementați cu:

type MyEnum = 'up' | 'down' | 'left' | 'right'

interface IProps {
  Size: MyEnum
}

ca const

MyEnum.Up    

Implementați cu:

const MyEnum = {
  Up: 'up',
  Down: 'down',
  Left: 'left',
  Right: 'right',
} as const

type MyEnum = typeof MyEnum[keyof typeof MyEnum]

// Example type
interface IProps {
  Size: MyEnum // string, without line `type MyEnum =...`
}

Mai multe detalii despre as const și înghețarea parametrilor