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

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
主站蜘蛛池模板: 芦溪县| 朝阳市| 峨眉山市| 城固县| 大化| 西城区| 马公市| 河西区| 霍州市| 福泉市| 广州市| 武邑县| 银川市| 马山县| 额济纳旗| 长白| 凌云县| 灵山县| 大城县| 永顺县| 阿合奇县| 惠来县| 中阳县| 淮阳县| 黔南| 寻甸| 三明市| 万州区| 辉南县| 昭觉县| 杂多县| 班玛县| 青龙| 苍南县| 山东省| 崇阳县| 江陵县| 仙居县| 奉化市| 西吉县| 宣恩县|