简体   繁体   English

我如何在Typescript reactjs中定义外部类方法?

[英]How do I define class methods outside it in typescript reactjs?

I want to use methods for the class as following: 我想为该类使用以下方法:

class MyComponent extends React.Component<Props> {
render() {
let { date } = this.props
let range = MyComponent.title(date)

return <TimeGrid {...this.props} range={range} eventOffset={15} />
}
}

My method is: 我的方法是:

MyComponent.title = date => {
return `My awesome week: ${date.toLocaleDateString()}`;
};

But I am getting error : 但是我得到了错误:

Property 'title' does not exist on type 'typeof MyComponent' 类型“ typeof MyComponent”上不存在属性“ title”

You component will look like this.Add static to your method title. 您的组件将如下所示。将static添加到您的方法标题中。

class MyComponent extends React.Component<Props> {
      static title=date => {
          return `My awesome week: ${date.toLocaleDateString()}`;
       };
      render() {
          let { date } = this.props
          let range = MyComponent.title(date)
          return <TimeGrid {...this.props} range={range} eventOffset={15} />
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ClassScript中将Class方法动态导出为独立函数? - How do I dynamically export Class methods as standalone functions in TypeScript? 如何在Javascript对象中定义方法? - How do I define methods in Javascript objects? 如何在 Mongoose model 中定义方法? - How do I define methods in a Mongoose model? 如何在 Typescript 中定义通用变量? - How do I define a generic variable in Typescript? 我如何定义一个父类方法,当从子类中调用该方法时,该方法定义了该子类上的方法? - How do I define a parent class method that when invoked from a subclass defines methods on that subclass? 如何在 ReactJS 中从“外部”访问组件方法? - How to access component methods from “outside” in ReactJS? 如何从类外部访问类中的方法 - How can I access methods inside a class from outside of class 如果我在原型上定义方法,该如何在构造函数中调用它们? - If I define methods on the prototype, how do I call them in the constructor? 如何正确使用 ReactJS 到达路由器与 TypeScript 和 ESLint? - How do I correctly use ReactJS Reach Router with TypeScript & ESLint? 如何在浏览器控制台或外部脚本中调用 Reactjs 组件上的方法? - How can I call methods on Reactjs components in the browser console or from an outside script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM