【问题标题】:Set default value of property of object passed on parameter to function将参数传递给函数的对象属性的默认值设置为函数
【发布时间】:2020-07-22 05:03:52
【问题描述】:

这个问题的主要区别是我希望将我的属性保留在对象内部,而不是解构。

export interface MapSettings {
  up: 'trueNorth' | 'runIn' | 'magneticNorth' | 'user';
  rotation?: number;
}

type MapProps = {
  settings: MapSettings;
};

export const Map: FunctionComponent<MapProps> = function Map({
  settings,
}) {

我想为settings.rotation 设置一个默认值,但我也想将其引用为settings.rotation,因为设置的属性比此处显示的要多得多,而且我知道值的来源。

这是我能想到的最佳答案:

export const Map: FunctionComponent<MapProps> = function Map({
  settings: { rotation: settingsRotation = 360, ...settings },
}) {

但它不允许我使用默认值 360 引用 settings.rotation

【问题讨论】:

  • 只需检查函数第一行中的属性,如果未设置则设置它

标签: javascript reactjs typescript


【解决方案1】:

只需检查并设置它:

export const Map: FunctionComponent<MapProps> = function Map({
  settings,
}) {
  settings.rotation = (settings.rotation || settings.roation === 0) ? settings.rotation : 360

【讨论】:

  • 我只是希望在构造函数中有一种方法。谢谢。
【解决方案2】:

默认值被称为{ someKey = 'defaultValue' } insead of `{ someKey: 'defaultValue' }

所以你可以这样写

{
   settings = { rotation: settingsRotation = 360 },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2016-03-08
    相关资源
    最近更新 更多