First of all, I'm coming for php background and I'm currently sort of building a middleware in react, the way I would do this would be something like:
class Middleware extends React.Component {
funcOne(data) {
return data;
}
funcTwo(data) {
return (
<div>
{ data }
<br />
{ this.funcThree('Third function') }
</div>
);
}
}
class MyComponent extends Middleware {
funcOne(data) {
return `Rewrite of ${data}`;
}
funcThree(data) {
return data;
}
render() {
return (
<div>
{ this.funcOne('First function') }
{ this.funcTwo('Second function') }
</div>
);
}
}
class MySecondComponent extends Middleware {
funcThree(data) {
return data;
}
render() {
return (
<div>
{ this.funcOne('First function') }
{ this.funcTwo('Second function') }
</div>
);
}
}
ReactDOM.render(
<div>
<MyComponent />
<hr />
<MySecondComponent />
</div>,
document.getElementById('root'),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>
However I can't really find any documentation on whether to do or not to do this. So, is this wrong? And if so, how should I do this instead?
In your updated code, just create a component for funcTwo
and pass a prop to it:
function funcOne () {
return 'First function';
}
function Two (props) {
return (
<div>
Second function
<br />
{ props.three }
</div>
);
}
//...
render() {
return (
<div>
{ funcOne() }
<br />
<Two three={this.funcThree()} />
</div>
);
}
I've never seen any use cases that must use inheritance in React. In your case, just create components or plain functions. Besides, a component can also be a plain function:
this can be a component:
function One (props) {
return <h1>hello</h1>
}
You use it like this:
<One />
Or, if you just need strings, simply write functions:
function funcOne () {
return 'First function';
}
function funcTwo () {
return 'Second function';
}
// ...
render() {
return (
<div>
{ funcOne() }
<br />
{ funcTwo() }
</div>
);
}
Thus you don't need inheritance at all. In JavaScript, especially React, you should try to think in a more functional way. You will find that it's very powerful and flexible.
You can find an official documentation about component composition here: https://facebook.github.io/react/docs/composition-vs-inheritance.html
I also recommend you to read this: https://facebook.github.io/react/docs/thinking-in-react.html