- Build Applications with Meteor
- Dobrin Ganev
- 326字
- 2021-07-09 19:48:54
Adding state to a stateless function component
What is a state in React's components?
Components can be declared as pure JavaScript functions, and they are called Stateless, such as this one:
function Greeting({ hello }) {
return <div>{hello}</div>;
}
Alternatively, you can write the preceding code as an ES6 arrow function:
const Greeting = ({ hello }) => (
<div>{hello}</div>
)
Every component can hold internal encapsulated data, and we call this a state of the component. If you want to add a state to a stateless component, you should define it as an ES6 class.
Before adding an ES6 constructor and super methods to the stateless components, we can overview what an ES6 constructor is and what the super method does in ES6 classes.
In ES6, we can create a class, such as the following:
class Component {
constructor(props){
this.props = props;
}
}
The names of the parameters and methods are named as React's once. This is not from the React library source.
We can add a method called render, as mentioned in the following code:
class Component {
constructor(props){
this.props = props;
},
render() {
return this.props;
}
}
In an ES6 classical way, we can extend the base/parent class Component:
class Greeting extends Component{
constructor(name){
super(name) // passing the value to the parent class which gets
assigned to the props
console.log(super.render()) // with the super method we can call the functions from the parent class
console.log(this.render()) // or directly as this.render
}
}
In a classical way, we can create a new instance of the Greeting class, like this:
let greet = new Greeting('Joe');
console.log(greet.render()) // have an access to the parent method render
We can create a render() method with the same name in the child class:
class Greeting extends Component{
constructor(name){
super(name)
this.name = name;
console.log(super.render())
}
render() {
return 'Hi ' + this.name;
}
}
let greet = new Greeting('Harry');
console.log(greet.render()) // child overrides the parent
- Ext JS Data-driven Application Design
- Instant QlikView 11 Application Development
- RISC-V體系結(jié)構(gòu)編程與實(shí)踐(第2版)
- Building RESTful Python Web Services
- Java Web開發(fā)就該這樣學(xué)
- 現(xiàn)代C++編程實(shí)戰(zhàn):132個(gè)核心技巧示例(原書第2版)
- Hands-On GUI Programming with C++ and Qt5
- Python大學(xué)實(shí)用教程
- 超好玩的Scratch 3.5少兒編程
- LabVIEW數(shù)據(jù)采集(第2版)
- C++ Data Structures and Algorithm Design Principles
- 少年小魚的魔法之旅:神奇的Python
- Learning Gerrit Code Review
- Server Side development with Node.js and Koa.js Quick Start Guide
- Learning Java by Building Android Games