Does the statics object work with ES6 classes in React?
class SomeComponent extends React.Component { render() { // ... } } React.statics = { someMethod: function() { //... } };
Something like the above gives me undefined method someMethod
when I do SomeComponent.someMethod()
statics only works with React. createClass . Simply declare the method as a static class method: class SomeComponent extends React.
ES6 introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class , and the properties are assigned inside a constructor() method.
So what are my recommendations for React components? You can use class in your JS if you don't inherit twice and don't use super. Prefer to write React components as pure functions when possible. Use ES6 classes for components if you need the state or lifecycle hooks.
React uses ES6, and you should be familiar with some of the new features like: Classes. Arrow Functions. Variables (let, const, var)
statics
only works with React.createClass
. Simply declare the method as a static class method:
class SomeComponent extends React.Component { static someMethod() { //... } render() { // ... } }
Regarding
React.statics = { ... }
You are literally creating a statics
property on the React
object. That property does not magically extend your component.
Although statics
only works for React.createClass
, you can still write static methods in ES6 notation. If you are using ES7, then you can also write static properties.
You can write statics inside ES6+ classes this way:
class Component extends React.Component { static propTypes = { ... } static someMethod(){ } }
Or outside the class like this:
class Component extends React.Component { .... } Component.propTypes = {...} Component.someMethod = function(){....}
If you want to write it like the former, then you have to set stage: 0
on Babel (since its experimental).
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