【问题标题】:Javascript: Export array with objects that refer to functionsJavascript:使用引用函数的对象导出数组
【发布时间】:2019-06-23 00:53:57
【问题描述】:

我正在使用一个数组来填充设置页面,并且一些按钮具有附加功能。

这就是我想要做的。 在一个文件中导出一个数组,其中包含引用同一文件中的函数的对象 要么 导出一个类,然后从该类中访问该数组,引用该类中的函数。

//导入文件

import Settings from './Settings';
console.log(Settings.settingsArray);

// 导出文件

export const settingsArray = [
  {
    title: " ",
    data: [
      {
        title: "Export data",
        func: this.exportData
      }
    ]
  },
  {
    title: " ",
    data: [
      { 
        title: "Set custom code",
        func: this.showDialog
      },
    ]
  }
]

exportData = () => {
    // some code
};

showDialog = () => {
    // some code
};

【问题讨论】:

  • 您的问题到底是什么?你遇到了什么问题?
  • this 不指代在此范围内有用的任何内容。 exportData 应该已经存在以便在数组中引用。它应该在没有this 的情况下被引用。
  • 嗯,我曾经拥有整个设置树,其中包含提供给整个应用程序的上下文中的每个功能。它工作得很好,除了不好的做法,直到我尝试使用 JSON.stringify 保存以响应本机 AsyncStorage,因为它不喜欢函数。所以我试图把它放在一个单独的文件中,现在我只需要弄清楚如何从那个文件连接到上下文。

标签: javascript arrays reactjs function object


【解决方案1】:

删除 this 关键字并在使用它们之前创建函数:

const exportData = () => {
    // some code
};

const showDialog = () => {
    // some code
};

export const settingsArray = [
  {
    title: " ",
    data: [
      {
        title: "Export data",
        func: exportData
      }
    ]
  },
  {
    title: " ",
    data: [
      { 
        title: "Set custom code",
        func: showDialog
      },
    ]
  }
];

或者将它们声明为functions 并利用提升。

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多