Skip to content Skip to sidebar Skip to footer

Passing Classes As React Props - Which Of The Two Implementations Is Correct?

This question should be an easy riddle for TypeScript/React hackers. I have a React component that passes a class-object to a child-component. Within the child-component, I call a

Solution 1:

Actually, the problem has nothing to do with React.

What is happening is that those two implementations behave slightly different one from each other.

The following code:

class Foo {
  constructor() {
    this.instanceMethod = function(): void {};
  }
  fooMethod: () => void;
}

const fooInstance = new Foo();

Declares a class with an instance method instanceMethod.

The following:

class Foo {
  prototypeMethod(): void {};
}

const fooInstance = new Foo();

Declares a class with a prototype method prototypeMethod.

When you use object destructuring syntax {...this.state} only own properties and methods (non prototype) are assigned.

So that is the reason why the first implementation works while the second throws an error.


Post a Comment for "Passing Classes As React Props - Which Of The Two Implementations Is Correct?"