Javascript 在 React ES6 类中调用静态函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35672135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:06:18  来源:igfitidea点击:

Call a static function into the class React ES6

javascriptreactjsecmascript-6

提问by Ajouve

I have the following ReactJS class:

我有以下 ReactJS 类:

import React from 'react'

export class Content extends React.Component {

  static getValue(key) {
    return key
  }

  render() {
    let value = this.getValue(this.props.valueKey);
    return <span dangerouslySetInnerHTML={{__html: value}} />
  }
}

But I have the following error:

但我有以下错误:

TypeError: this.getValue is not a function

I don't understand. Is this the good way to call a static function? I think react is doing something with statics, but I don't know what.

我不明白。这是调用静态函数的好方法吗?我认为 react 正在做一些静态的事情,但我不知道是什么。

回答by Cymen

A static method needs to be accessed on the class not an instance. So in your case, use:

需要在类而不是实例上访问静态方法。因此,在您的情况下,请使用:

Content.getValue()

Content.getValue()

However, a static method won't be able to access this-- I don't think you want the method to be static based on your code sample above.

但是,静态方法将无法访问this——根据上面的代码示例,我认为您不希望该方法是静态的。

More: Static Members in ES6

更多:ES6 中的静态成员

回答by Geoffrey Abdallah

You can access from within the class as this.constructor.getValue.

您可以作为this.constructor.getValue.

Edit: I've added a JSFiddle here. The only change I made was adding the function call from the constructor and removing the dangerously set innerHTML - As shown, you can access the getValue static from this.constructor, and works just fine.

编辑:我在这里添加了一个 JSFiddle 。我所做的唯一更改是从构造函数添加函数调用并删除危险设置的 innerHTML - 如图所示,您可以从 this.constructor 访问 getValue 静态,并且工作正常。