- Create React App 2 Quick Start Guide
- Brandon Richey
- 369字
- 2021-07-02 12:53:28
Writing a class-based component
In ECMAScript 6 (ES6), we got our first taste of real object-oriented programming in JavaScript with Classes. A class is declared in a fundamentally different way than our functional components, but most of the core tenets remain the same and there's not a huge amount more we need to learn to start using them.
The first thing we'll need to do is make a small modification to the import statement in src/Todo.js. We'll need to import not just React itself: we'll also need to import a particular named export specified in React, something called Component. Let's take a look at what the new import statement looks like:
import React, { Component } from 'react';
We have our Component imported as well, so let's explore the syntax for declaring a class:
class Todo extends Component { /* ... */ }
This tells JavaScript that we're building a new Todo class that inherits the functionality of Component (thus the extends keyword). Next, any React component we build as an ES6 class needs to have a render() function declared. To declare a function inside of a class, you just write the name, the arguments, and then the body inside of your class definition:
functionName(argument1, argument2) { /* ... */ }
React specifically requires us to declare a render() function with no arguments, as we mentioned earlier. Our return statement is identical to what we had in our previous functional component, so putting everything together we should end up with something similar to this:
class Todo extends Component {
render() {
return <div className="Todo">{this.props.description}</div>;
}
}
Here, we write out our render() { … } function, which is largely unchanged except for one small change: props.description is now this.props.description!
The reason for this is that props is not something that is just an argument on a function anymore. It's actually part of a class-specific property, so we need to tell JavaScript that when we say props, we actually mean the props local to this class. We just shorthand that with this.props! With that out of the way, we can start diving even further into the world of state!
- HTML5移動(dòng)Web開發(fā)技術(shù)
- CockroachDB權(quán)威指南
- ASP.NET MVC4框架揭秘
- Python自然語言處理實(shí)戰(zhàn):核心技術(shù)與算法
- C語言程序設(shè)計(jì)立體化案例教程
- JS全書:JavaScript Web前端開發(fā)指南
- Learning Apache Mahout Classification
- Swift細(xì)致入門與最佳實(shí)踐
- 編程與類型系統(tǒng)
- RealSenseTM互動(dòng)開發(fā)實(shí)戰(zhàn)
- Statistical Application Development with R and Python(Second Edition)
- Building Dynamics CRM 2015 Dashboards with Power BI
- Unity 2017 Game AI Programming(Third Edition)
- Xamarin Cross-Platform Development Cookbook
- 軟件再工程:優(yōu)化現(xiàn)有軟件系統(tǒng)的方法與最佳實(shí)踐