官术网_书友最值得收藏!

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
主站蜘蛛池模板: 罗江县| 高密市| 淮安市| 集安市| 清镇市| 垣曲县| 九寨沟县| 江阴市| 苍山县| 中卫市| 讷河市| 金乡县| 宜兰市| 磐石市| 西乌珠穆沁旗| 黑水县| 斗六市| 甘谷县| 察隅县| 北京市| 罗源县| 宁国市| 集安市| 三河市| 金塔县| 滕州市| 南汇区| 敖汉旗| 凤冈县| 田林县| 大竹县| 灌阳县| 轮台县| 三台县| 哈尔滨市| 子长县| 中牟县| 富裕县| 武穴市| 清原| 武义县|