[英]Call a static function into the class React ES6
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.
我认为反应是用静电做的,但我不知道是什么。
A static method needs to be accessed on the class not an instance. 需要在类而不是实例上访问静态方法。 So in your case, use:
所以在你的情况下,使用:
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中的静态成员
You can access from within the class as this.constructor.getValue
. 您可以在类中以
this.constructor.getValue
进行访问。
Edit: I've added a JSFiddle here . 编辑:我在这里添加了一个JSFiddle。 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.
我做的唯一改变是从构造函数添加函数调用并删除危险的setHTML - 如图所示,您可以从this.constructor访问getValue静态,并且工作得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.