React-組件的自訂涵式兩種寫法

組件的自訂涵式兩種寫法

第一種(箭頭涵式)

詳細資料請看上一篇文章(React-組件的事件處理和狀態更新)

第二種(一般涵式)

使用一般涵式,則需要將this重新綁定,
所以建議使用箭頭涵式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React, {Component} from 'react';     //載入react核心

class Message extends Component{ //創建一個Message組件
//組件狀態
state = {
'title': 'Hello',
'name': 'John'
};

//constructor(建構子)是個隨著 class 一同建立並初始化物件的特殊方法
//預設的建構子長得像這樣
//constructor(props){
// super(props)
//}

constructor(props){
super(props)
//super() 必須在使用 this 以前被呼叫。不這樣的話會發生錯誤。

//將this.changeName永遠綁定(bind)在自己身上(this)
this.changeName = this.changeName.bind(this)
}

//自訂涵式(使用一般涵式)
//如果沒有使用constructor(),則this綁定在buttn身上
changeName() {
this.setState({
'name': 'Bob',
})
}

//生命週期內的涵式
render() {
return(
<div> //this指向此組件
<h1> { this.state.title } </h1>
<h3>I am { this.state.name }</h3>
<button onClick= {this.changeName}>更改state</button>
</div>
)
}
}

export default Message;
分享到