gpt4 book ai didi

reactjs - 在 React ES6 类中调用方法

转载 作者:行者123 更新时间:2023-12-02 11:20:10 25 4
gpt4 key购买 nike

我有以下 react 类

export default class ValClass { 
getValue (key) {
return key;
}
}

import React from 'react'
import ValClass from 'valclass'

export class Content extends React.Component {

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

But I have the following error:

TypeError: _valClass2.default.getValue is not a function.

如果我这样编码

export default class ValClass { }
ValClass.getValue (key) {
return key;
}

import React from 'react'
import ValClass from 'valclass'

export class Content extends React.Component {

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

然后就可以正常工作了。怎么办?

最佳答案

原因是,您直接使用 this函数定义为静态关键字将无法访问。

根据 DOC :

Static method calls are made directly on the class and are not callableon instances of the class.

Static methods are not directly accessible using the this keyword fromnon-static methods. You need to call them using the class name:CLASSNAME.STATIC_METHOD_NAME() or by calling the method as a propertyof the constructor: this.constructor.STATIC_METHOD_NAME().

In order to call a static method within another static method of thesame class, you can use the this keyword.

在您的情况下,我认为您不需要 static 方法,而不是将其定义为 static,而是像这样编写:

class Content extends React.Component {

getValue() {
return "<div> Hello </div>";
}

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

ReactDOM.render(<Content/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

更新:

您改变了原来的问题,如果您定义了另一个类并想要调用该类的函数,那么您需要将其定义为静态。

class Content extends React.Component {

render() {
let value = App.getValue();
return <div dangerouslySetInnerHTML={{__html: value}} />
}
}

class App {
static getValue() {
return "<div> Hello </div>";
}
}

ReactDOM.render(<Content/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

关于reactjs - 在 React ES6 类中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com