I understand that my question is a little bit biased, but I am very new in Javascript and prototypes
, and I read about it, but I don't really understand how to apply that techniques to my practical problems. So an example would be very helpful.
So I have a React
component, that basically looks like that:
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 absolutely the same, but has one additional <input/>
inside the return
of its render
function.
I also have Component3
, which shares same functions, but has different render()
function.
So how to apply inheritance here and avoid copy-paste 3 times? I just miss some practical illustration, so I'd appreciate it.
Edit1____________________________________________________
So I tried to implement Prototype inheritance as per the first answer, but it seems React doesn't see these functions: getInitialState()
is null, initial state is null after rendering. What's wrong with this approach?
I also tried to go according to the textbook 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 my browser, I get an error: Uncaught Invariant Violation: createClass(...): Class specification must implement a
rendermethod.
What am I doing wrong this way?
Edit2_______________________________________________
Actually, I see that React doesn't support mixins neither prototypes. Composition should be used instead. It's explained in this article: Dan Abramov's article Mixins Are Dead. Long Live Composition