箭头函数不显示 React class 原型

Arrow function not show with React class prototype

我正在尝试在 React class 组件中记录所有功能 class,搜索网络并到处询问,我得到了这个

const listOfFunctionClass = Object.getOwnPropertyNames(MyClass.prototype)

有效!但问题是当我尝试记录时它只显示生命周期和函数 console.log(listOfFunctionClass)不包括箭头函数

例子

class Foo extends React.Component{
  functionA(){} ==>will log
  functionB = () =>{}  ===> will not show on log
  componentDidUpdate() ==> will log on log
}

它将有一个类似 [functionA, componentDidUpdate]

的数组

那么如何在 proptype 上添加箭头功能呢?

虽然从技术上讲,您可以通过分配给 .prototype 属性 外部来在原型上添加箭头函数:

class Foo extends React.Component {
}
Foo.prototype.fn = () => {
  // ...
}

由于箭头函数的工作方式,您将无法访问其中实例的 this。这样的箭头函数只有在它需要的所有数据都传递给它时才可用。

但在大多数情况下使用标准方法会更有意义

class Foo extends React.Component {
  fn() {
    // ...

或一个class字段

class Foo extends React.Component {
  fn = () => {

您无法轻松检测 class 上的 class 字段,因为它们是

的语法糖
class Foo extends React.Component {
  constructor() {
    this.fn = () => {

它们不在原型上——它们只在实例上。您必须检查实例本身以查看它具有哪些属性才能找到这样的 class 字段。

const builtinReactInstanceProperties = ['props', 'context', 'refs', 'updater'];
class Foo extends React.Component {
  fn = () => {}
}
const instance = new Foo();
console.log(
  Object.getOwnPropertyNames(instance)
    .filter(propName => !builtinReactInstanceProperties.includes(propName))
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

就是说,这种对对象上存在哪些属性的动态分析非常奇怪。我想不出什么时候这种方法是最好的。