代码之家  ›  专栏  ›  技术社区  ›  CODEforDREAM

React类原型中未显示箭头函数

  •  0
  • CODEforDREAM  · 技术社区  · 2 年前

    我试着把所有函数类记录在React类组件中,搜索网页,到处询问,我得到了这个

    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上添加箭头函数呢?

    1 回复  |  直到 2 年前
        1
  •  1
  •   CertainPerformance    2 年前

    而从技术上讲,您可以通过将 .prototype 境外物业:

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

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

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

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

    或者一个班级

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

    您无法轻松检测类上有哪些类字段,因为它们是糖的语法

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

    它们不在原型上——它们只在实例上。为了找到这样一个类字段,您必须检查实例本身,看看它有什么属性。

    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>

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