One can create a component in React with the following syntax:
import React, { Component } from 'react';
import ChildComponentOne from './ChildComponentOne';
import ChildComponentTwo from './ChildComponentTwo';
class App extends Component {
constructor(props) {
super(props);
this.state = {
propOne : '',
propTwo : '',
propThree : '',
};
this.doThis = this.doThis.bind(this);
this.doThat = this.doThat.bind(this);
}
doThis() {
...doingThis code
}
doThat() {
...doingThat code
}
render() {
return (
<ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
<ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
);
}
}
export default App;
Does React utilize this class syntax because they're trying to make a encapsulated and tidy notation for organizing components. And everything else after the constructor method is centric to React.
Or is is possible to write something like this:
App.prototype.doThis = function(){};
App.prototype.doThat = function(){};
function App(){
this.state = {
propOne : '',
propTwo : '',
propThree : '',
};
componentDidMount(){...somecode..}
componentWillUnmount(){...somecode..}
render(){
return (
<ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
<ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
);
}
}
I know I am not too far off as one can utilize just a regular function to create a so-called functional component
.
Guess the question would be how to utilize the life-cycle methods...
ES6 classes are syntactic sugar for function classes. They actually become functions when the application is transpiled to ES5.
React class components are expected to have render
method and prototypically inherit from React.Component
, this is how they differ from functional components.
render
should preferably be prototype method:
App.prototype = Object.create(Component.prototype);
App.prototype.render = function () { ... };
function App(props) { ... }
Because this.render = ...
instance method isn't justified. Also it may expected to be prototype method by some third-party libraries.