# 組件定義
## 函數定義
定義一個React組件可以使用一個函數,具體如下
```jsx
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
ReactDOM.render(
<Welcome name='xiaoyu'/>,
document.getElementById('root')
);
```
可以在瀏覽器中看到輸出 "Hello, xiaoyu"。
在這個例子中,使用 `function` 定義了一個名叫 `Welcome` 的組件,使用 `ReactDOM.render` 渲染組件的時候可以將 `Welcome` 作為一個標簽的形式使用,這個組件接受一個屬性值的參數,渲染了傳入的`name`屬性。
## 類定義
定義一個React組件還可以使用ES6的class定義,具體如下
```jsx
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(
<Welcome name='xiaoyu'/>,
document.getElementById('root')
);
```
最終渲染效果與之前用 function 定義的組件相同。
這里,使用類定義了一個組件,必須繼承 `React.Component` 類以確保此類是一個React組件,重寫父類中的 `render()` 方法進行頁面渲染。
### 將函數轉換為類
可以通過5個步驟將函數組件轉換為類組件
1. 創建一個名稱擴展為 React.Component 的ES6 類
2. 創建一個叫做render()的空方法
3. 將函數體移動到 render() 方法中
4. 在 render() 方法中,使用 this.props 替換 props
5. 刪除剩余的空函數聲明
## React元素可以是用戶自定義的組件
比如改寫上面使用類定義的組件:
```jsx
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
let name = 'xiaoyu'
const element = <Welcome name={name} />
ReactDOM.render(
element,
document.getElementById('root')
);
```
>[warning] 再次強調: 組件名稱必須以大寫字母開頭。
## 組合組件
組件可以相互組合、嵌套:
```jsx
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="xiaoyu" />
<Welcome name="xiaoqiao" />
<Welcome name="xiaoming" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
>[warning] 組件的返回值只能有一個根元素。這也是為什么要用一個\<div>來包裹所有\<Welcome />元素的原因。
## 點表示法
可以使用 JSX 中的點表示法來引用 React 組件,這樣可以方便地從一個模塊中導出許多 React 組件。
例如,有一個名為 MyComponents.DataPicker 的組件,可以直接在 JSX 中使用它:
```jsx
import React from 'react';
const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}
function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;
}
```
- 簡介
- 第一章 React入門
- 1.1 創建一個React項目
- 1.2 組件
- 1.3 JSX
- 1.4 eject
- 1.5 渲染
- 第二章 React組件
- 2.1 組件定義
- 2.2 數據處理
- 2.2.1 props
- 2.2.2 state
- 2.3 生命周期
- 2.3.1 裝載過程
- 2.3.2 更新過程
- 2.3.3 卸載過程
- 2.4 事件處理
- 2.5 條件渲染
- 2.6 列表渲染
- 第三章 React高級
- 3.1 靜態類型檢查
- 3.1.1 flow
- 3.1.2 typescript
- 3.2 React Developer Tools
- 第四章 Redux狀態管理
- 4.1 安裝與配置
- 4.2 一個簡單的計數器開始
- 4.3 Store
- 4.3.1 獲取state
- 4.3.2 subscribe
- 4.4 Action
- 4.4.1 Action Creators
- 4.5 Reducer
- 4.5.1 Reducer 的拆分
- 4.6 與其他狀態管理工具的對比
- 第五章 React-Router路由
- 參考資料