- 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
- JavaScript百煉成仙
- Access 數(shù)據(jù)庫應用教程
- Reactive Programming with Swift
- Unity Virtual Reality Projects
- 三維圖形化C++趣味編程
- Oracle BAM 11gR1 Handbook
- 用Flutter極速構(gòu)建原生應用
- Mastering Linux Network Administration
- 全棧自動化測試實戰(zhàn):基于TestNG、HttpClient、Selenium和Appium
- INSTANT Sinatra Starter
- SQL 經(jīng)典實例
- 匯編語言編程基礎:基于LoongArch
- 汽車人機交互界面整合設計
- Getting Started with RethinkDB
- HTML5程序設計基礎教程