如何在 ES6 类中声明公共函数

How can I declare a public function in an ES6 class?

本文关键字:声明 函数 ES6      更新时间:2023-09-26

我正在尝试在 React ES6 类扩展 React.Component 中添加一个公共函数。但是,我尝试过的任何方法都没有使该功能公开提供给其他组件。

欢迎任何提示。

以下是我尝试过的一些示例:

import React, { PropTypes } from 'react'
import ChildComponent from './ChildComponent'
export class ArticleModal extends React.Component<void, Props, void> {
  static propTypes = {
  };
  constructor (props) {
    super(props)
  }
  static privateMethod () {
    // This doesn't work
  }
  set privateMethod2 () {
    // This doesn't work either
  }
  privateMethod3 () {
    // ...and neither does this.
  }
  render () {
    return (
      <p>Some content</p>
    )
  }
}
const mapStateToProps = (state) => ({
})
export default connect((mapStateToProps), {
})(ArticleModal)

像这样修改构造函数

constructor (props) {
    super(props);
    this.privateMethod3 = this.privateMethod3.bind(this);
}

然后尝试调用私有方法3