【问题标题】:Exporting a function within a class in Typescript在 Typescript 中的类中导出函数
【发布时间】:2019-02-05 17:18:54
【问题描述】:

我正在尝试在 Typescript 的类中导出一个函数。我能够导出该类,并将其用作另一个类中的导入。但是,当我尝试使用该功能时,它给了我如下错误

“typeof Landing”类型上不存在属性“formatBytes”。

我正在尝试在Landing 类中导出函数formatBytes 并将其用作Landing.formatBytesModules 类中。

导出的类

import * as React from 'react';

export default class Landing extends React.Component<{}, SomeState> {
public formatBytes(bytes: number, decimals: number): string {

return 'something';
}

public componentDidMount(): void {

// code
}


public render(): JSX.Element {
const { items } = this.state;

return (
  <div>

  </div>
);
}
}

导入类

import * as React from 'react';
import Landing from './Landing'

export default class Modules extends React.Component<
{},
IDetailsListModulesState
> {

constructor(props: {}) {
super(props);

const _columns: IColumn[] = [
  {
    onRender: (item: IDetailsListModuleItem) => {
      return (
        <span>
          {Landing.formatBytes(item.sizeDifference, 3)}
        </span>
      );
    }
  },
];

this.state = {
};
}

public componentDidMount(): void {

}

public render(): JSX.Element {

}
}

【问题讨论】:

    标签: typescript export


    【解决方案1】:

    必须实例化 Landing 类才能使用formatBytes 方法。通过执行以下操作实例化一个新的 Landing 实例:

    const myLanding = new Landing();
    myLanding.formatBytes(item.sizeDifference, 3);
    

    或者通过写 public static formatBytes... 使 formatBytes 成为静态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多