Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a static function from a component instance in react?

I have a component with a number of static functions defined for it(through the statics property in the component definition). I need to access one of these static functions in the lifecycle method componentDidMount. I tried the following

  • this object has a statics property, but that seems to be null always
  • this object also has a _owner, which in turn has a statics property. Again, that is always null

Then I tried this.constructor.<static_function>. This worked for me. I just wanted to know whether this is the right way to access static functions defined for a component or is there something else that I am unaware of.

like image 263
Jophin Joseph Avatar asked Mar 19 '15 14:03

Jophin Joseph


2 Answers

Accessing your static methods and properties via this.constructor is fine. You can also access them via ComponentClass.<static>.

like image 94
Alexandre Kirszenberg Avatar answered Sep 20 '22 02:09

Alexandre Kirszenberg


Why not define the functions in the outer scope, and just export them in the statics property. Something like this:

var foo = function() { ... }
var bar = function() { ... }

var MyComponent = React.createClass({
  statics: {
    foo: foo,
    bar: bar
  }
});

Now the static functions are accessible anywhere in the scope of the component code.

like image 24
Breno Ferreira Avatar answered Sep 22 '22 02:09

Breno Ferreira