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

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
主站蜘蛛池模板: 张家界市| 苏州市| 江城| 江津市| 瑞丽市| 重庆市| 苍梧县| 延津县| 杭锦旗| 东阳市| 宁强县| 隆安县| 余干县| 阿鲁科尔沁旗| 渭源县| 芒康县| 新巴尔虎左旗| 斗六市| 大新县| 阳泉市| 顺昌县| 苍溪县| 通榆县| 渭源县| 股票| 缙云县| 唐河县| 东乌| 安平县| 平定县| 杭锦后旗| 兴化市| 邛崃市| 湄潭县| 革吉县| 西城区| 寻甸| 库伦旗| 崇文区| 白河县| 通江县|