React學習之旅Part5:React組件的class創建方式及傳值和傳遞方法、state私有數據、有狀態組件和無狀態組件

Class創建組件

React創建組件有兩種方式 一種是function創建方式
具體可以看我這篇博客:React學習之旅Part4:React組件的function創建方式及傳值、抽離爲單獨jsx文件

還有一種更常用且推薦的 就是class創建方式

class方式創建組件 有三個需要注意的地方:

  • 1、若要使用class關鍵字來定義組件 則必須讓組件繼承React.Component
  • 2、在組件裏必須用render函數渲染 否則會報錯
  • 3、必須返回合法的JSX虛擬DOM結構 若沒有要返回的內容 則return null
import React from 'react'
import ReactDOM from 'react-dom'

// 若要使用class關鍵字來定義組件 則必須讓組件繼承React.Component
class Hello extends React.Component
{
    // 必須用render函數渲染
    render()
    {
        // 必須返回合法的JSX虛擬DOM結構
        return <h1>Hello</h1>
    }
}

ReactDOM.render(<div>
    Test
    <Hello></Hello>
</div>,document.getElementById("app"))

傳遞參數

在class關鍵字創建的組件中 若想使用外界傳來的props參數 無需接收
直接通過this.props.xxx即可訪問
在class組件內部 this表示當前組件的實例對象

class Hello extends React.Component
{
    render()
    {
        return <h1>Hello{this.props.name}{this.props.age}</h1>
    }
}

const user={
    name:"陳濤",
    age:18
}

ReactDOM.render(<div>
    Test
    <Hello></Hello>
    <hr/>
    {/* 傳遞參數 */}
    <Hello {...user}></Hello>
</div>,document.getElementById("app"))

...是ES6的展開運算符 對象裏面有多少屬性 就傳遞多少屬性
name={user.name} age={user.age}意義相同

傳遞方法

傳遞方法的方式和傳遞屬性一樣 也是在子組件上通過<Son yyy={this.xxx}><//Son>傳遞
然後在子組件內使用this.props.yyy調用
相對於Vue的傳遞方法 在React中傳遞方法要簡單多了😊

私有數據(this.state)

使用class關鍵字方式創建的組件擁有其自己的私有數據
但使用function方式ic換件的組件 只有props 並沒有自己的私有數據和生命週期函數
因此 可以理解爲 用class方式創建的組件會 更加全

this.state設置私有數據 相當於Vue的data(){ return {} }
這是可讀可寫

class Hello extends React.Component
{
    constructor()
    {
        super();
        // 爲組件綁定私有數據
        this.state={
            msg:"Hello World"
        }// 相當於Vue的data(){ return {} } 可讀可寫
    }

    // 必須用render函數渲染
    render()
    {
    	// 設置數據
        this.state.msg="Hello!"
        return <h1>
            Hello
            <span>{this.state.msg}</span>
        </h1>
    }
}

ReactDOM.render(<div>
    Test
    <Hello></Hello>
</div>,document.getElementById("app"))

有狀態組件和無狀態組件

使用class關鍵字方式創建的組件擁有其自己的私有數據(this.state)和生命週期函數
而 使用function方式創建的組件 並沒有其自己的私有數據和生命週期函數

因此 用function構造函數創建的組件 被稱爲無狀態組件(使用頻率不高)
而用class關鍵字創建的組件被稱爲有狀態組件

有狀態組件和無狀態組件的本質區別有無state屬性生命週期函數 (state英文翻譯過來就是狀態)

組件中props和state的區別

  • props中的數據都是外界傳入到組件內的
    state中的數據是組件私有的(通常是Ajax獲取的數據)

  • props中的數據都是只讀的 並不能重新爲其賦值
    state中的數據是可讀可寫


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章