Static methods in reagent

I went through the React documentation and ran into a static method. I was wondering in which scenario this could be useful and could not come up with.

Is there a specific scenario in which static methods are useful when creating components in React?

+5
source share
1 answer

defaultProps and propTypes are static elements of React components, they are not changed for each instance. See https://facebook.imtqy.com/react/docs/reusable-components.html

One example of static properties is the ability to track how many instances of an object have been created (and not for a specific answer). Note that most of the time, static methods are the smell of code if you change state.

 var Contacts = React.createClass({ statics: { instanceCount: 0 }, getInitialState: function() { Contacts.instanceCount++ return {}; }, render: function() { return (<div > Hello { this.props.name } < /div>); } }); console.log(Contacts.instanceCount) // 0 ReactDOM.render( < Hello name = "World" / > , document.getElementById('container') ); console.log(Contacts.instanceCount) // 1 

Another example is a method for storing constants.

 var Contacts = React.createClass({ statics: { MAX_VALUE:100 }, render: function() { return (<div > Hello { this.props.name } < /div>); } }); if (someValue > Contacts.MAX_VALUE) { } 
+6
source

Source: https://habr.com/ru/post/1246153/


All Articles