6

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.

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean via this.constructor. How is that?
@Green e.g. You can use this.constructor.myStaticFunction() to access a function declared in your component with static myStaticFunction() { }.
6

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.

1 Comment

I usually use this method, perhaps there is better? I don't know - but this works just fine. Naturally you want to make sure that your component is scoped correctly so you don't leak, but that should be occuring anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.