# 基于class關鍵字創建組件
Class組件稱之為有狀態組件。即組件的私有狀態 。
## 使用 class 關鍵字來創建組件
在學習的過程中先書寫 如下代碼,通過報錯提示得知:在class創建的組件中,必須定義一個render函數
```
class Hi extends React.Component{
}
```
把render(){}函數書完完畢后,又會報錯得知:在render函數中,必須返回一個null或者符合規范的虛擬DOM元素
```
class Hi extends React.Component{
// 通過報錯提示得知:在class創建的組件中,必須定義一個render函數
render(){
}
}
```
最終我們可以書寫成以下的代碼
```
class Hi extends React.Component{
// 通過報錯提示得知:在class創建的組件中,必須定義一個render函數
render(){
// 在render函數中,必須返回一個null或者符合規范的虛擬DOM元素
return <div>
<h1>這是用 class 關鍵字創建的組件!</h1>
</div>;
}
}
```
## 組件通信-父向子傳遞數據
### 演示學習
普通構造函數定義的子組件是通過形參書寫props來接收父組件傳遞的數據。
class定義的子組件該如何接收父組件傳遞的數據?能直接按下面寫代碼?
```
class Hi extends React.Component{
render(){
return <div>
<h1>你好{props.name}年齡是{props.age}</h1>
</div>;
}
}
var obj = {
name:'小白',
age:16
}
ReactDom.render(<Hi {...obj}/>,document.getElementById('root'))
```
肯定是不可以按照上面的方式書寫會報錯。`Uncaught ReferenceError: props is not defined`props沒有定義。
### 正確思路
我們知道在學習Class類時候我們還有個constructor構造函數。這里面是可以傳值的。
~~~
class Hi extends React.Component{
constructor(props){
super(props); //super寫在構造函數的第一行
}
render() {
return(
<div>你好{this.props.name}年齡是{this.props.age}
</div>
);
}
}
~~~
在constructor中接收父組件傳遞的值。還要記得必須寫super(props)因為組件是繼承過來的
## webstormJS模板
我們發現每次為了書寫一個class組件,要寫很多單詞中,一不小心就會出錯。我們可以去配置webstorm的模板。

### 模板文件需要先拷貝
```
import React,{Component} from 'react';
export default class $className$ extends Component{
constructor(props){
super(props);
this.state = {}
}
render() {
return (
<div>這是$name$$end$組件</div>
);
}
}
```





### 使用
新建tabbar.js在文件中書寫react會立即生成我們想要的Class組件。
- webpack復習
- React基礎
- 前端三大主流框架對比
- React中幾個核心的概念
- React基礎語法
- React JSX語法
- React組件
- 普通組件
- 組件通信-父向子傳遞
- 組件拆成單個文件
- 面向對象復習
- Class組件基礎
- Class組件的私有狀態(私有數據)
- 案例:實現評論列表組件
- 組件樣式管理
- 組件樣式分離-樣式表
- CSS模塊化
- 生命周期
- React組件生命周期
- Counter組件來學習組件生命周期
- 生命周期總結
- 生命周期案例
- React評論列表
- React雙向數據綁定
- React版todolist
- 其它提高(了解)
- 組件默認值和數據類型驗證
- 綁定this并傳參的三種方式
- 祖孫級和非父子組件傳遞數據(了解)
- React路由
- 路由基礎
- 動態路由
- 路由嚴格模式
- 路由導航定位
- 路由重定向
- 路由懶加載
- WolfMovie項目
- 項目初始化
- AntDesign使用
- 其它相關了解