簡體   English   中英

箭頭 Function(TypeScript,React)中帶接口的默認值

[英]Default Values with Interface in Arrow Function (TypeScript, React)

這個問題是特定於箭頭函數的。 是否可以在 function 參數中的接口旁邊包含默認值,而不使用 Object.assign()?

interface Props {
  someBoolean?: boolean;
  anotherBoolean?: boolean;
  children: any;
}

const DefaultValues = {
  someBoolean: false,
  anotherBoolean: false,
}

export const StackOverflow: React.FC<Props> = (_props: Props) => {
  const props = Object.assign({}, _props, DefaultValues);

  return <React.Fragment>{props.children}</React.Fragment>;
};

如果您不需要其他地方的DefaultValues並且您不需要能夠引用 function 正文中的(所有) props ,那么是的:

export const StackOverflow: React.FC<Props> = ({ someBoolean = false,
  anotherBoolean = false, children = [], ...additionalProps }) => {

  return <React.Fragment>{children}</React.Fragment>;
};

您可以通過組合組件以功能方式提供默認值。

interface Props {
  someBoolean: boolean;
  anotherBoolean: boolean;
  children: any;
}

const StackOverflow: React.FC<Props> = (props: Props) => {
  return <React.Fragment>{props.children}</React.Fragment>;
};

function withDefaults<T extends React.ComponentType<any>, U extends Partial<React.ComponentProps<T>>>(
  Component: T,
  defaults: U,
): React.FunctionComponent<Omit<React.ComponentProps<T>, keyof U> & Partial<U>> {
  // @see https://github.com/Microsoft/TypeScript/issues/14729
  return props => React.createElement(Component, { ...defaults, ...props });
}

用法:

const StackOverflowWithDefaults = withDefaults(StackOverflow, { someBoolean: false, anotherBoolean: false });

<StackOverflowWithDefaults>
  The only prop I need to provide is children
</StackOverflowWithDefaults>

答案是否定的。 您不能向interfacetype添加一些默認value

但是你可以做這樣的事情。

interface SomeType {
     prop1: string;
     prop2: number;
     prop3?: boolean; // optional
}

const fun = (value: SomeType) => {

// Assigning default value to the prop3 which is optional.
   const {prop1, prop2, prop3 = false} = value;

}

暫無
暫無

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

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