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

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
主站蜘蛛池模板: 闽侯县| 长顺县| 历史| 惠安县| 泰州市| 瓦房店市| 剑阁县| 芦溪县| 吐鲁番市| 贵德县| 连江县| 密山市| 绥中县| 博乐市| 新昌县| 紫阳县| 合山市| 吉首市| 大渡口区| 德令哈市| 黑山县| 鄂伦春自治旗| 开平市| 溆浦县| 淄博市| 桃江县| 四川省| 建瓯市| 桓台县| 津南区| 育儿| 彰化市| 上林县| 福州市| 钦州市| 泸西县| 张家口市| 马边| 满洲里市| 阿荣旗| 武威市|