Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in a react component, how to get `this` in static function?

attempting to create a static function within a react component. the function uses this to get its data, but this is out of scope when the function is called.

here is a very simple example:

var Test = React.createClass({
  val: 5,
  statics: {
    getVal: function() { return this.val }
  },
  render: return( <div>{this.val}</div> )
});

Test.getVal(); => undefined!!

obviously this has lost its scope when Test.getVal() is called. how to get this inside the getVal() function?

fyi, the following standard javascript parent approach does not work:

Test.getVal.apply( Test ); => undefined
like image 639
cc young Avatar asked Jul 23 '15 04:07

cc young


1 Answers

Check out the docs on statics.

Whatever you put in statics is not going to have the context of an actual React component instance, but the val property you're defining is a property of an actual React component instance. It's not going to exist before you actually render the component, because that's when all the non-static properties are constructed. Statics are supposed to be component-related functions that are usable outside the context of an actual instance, just like for example static functions in C# and many other languages.

It simply doesn't seem to make sense to want to access a React component instance from a statics function. Maybe you need to think over what you're actually trying to achieve. If you really want to be able to access a specific component's properties, then I guess you can pass the instance as an argument to the static function, but then of course that would be usable once you have actually constructed a component.

like image 53
Hannes Johansson Avatar answered Sep 23 '22 16:09

Hannes Johansson