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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With