I understand that my question is a bit biased, but I am very new to Javascript and prototypes , and I read about it, but I really don't understand how to apply these methods to my practical problems. Thus, the example will be very useful. Therefore, I have a React component that basically looks like this:
var Component1 = React.createClass({ getInitialState: function () { return ({ searchable: true, }) }, function1: function () { return ({ somevalue }) }, render: function () { var redText = { color: 'red' }; var redBorder = { color: 'red', border: '1px solid red' }; return ( <form> <div> <a onClick={this.props.handleAddClick}>Something</a> </div> <div> <label>Some label</label> <input type="text"/> </div> </form> ) });
I also have Component2 , which is basically the same, but has another <input/> inside the return its render function.
I also have Component3 that shares the same functions but has a different render() function.
So how to apply inheritance here and avoid copy-paste 3 times? I just skipped some practical illustration, so I would appreciate it.
Edit1 ____________________________________________________ Therefore, I tried to implement Prototype inheritance according to the first answer, but React does not seem to see these functions: getInitialState() is null, the initial state is null after rendering. What is wrong with this approach?
I also tried to go according to the tutorial and did:
function MyPrototype() {}; MyPrototype.prototype.getInitialState = function () { return ({ someProperty: true; }) }; function Component1() {}; Component1.prototype = Object.create(MyPrototype.prototype); Component1.prototype.render = function () { console.log(this); return (<div></div>)}; var MyComponent1 = React.createClass(new Component1());
But when I open the browser, I get an error: Uncaught Invariant Violation: createClass(...): Class specification must implement a render method.
What am I doing wrong like that?
Edit2 _______________________________________________
Actually, I see that React does not support mixins and prototypes. Instead, use a composition. This is explained in this article: Dan Abramov's Mixins article is dead. Long live composition