一、 Props
1. props vs state
props state
props get passed to the component state is managed within the component
function parameters variables declared in the function body
props are immutable state can be changed
props - functional components useState Hook - functional components
this.props - class components this.state - class components
注意:react 只允許返回一個元素。
2. state
1). 不要直接更改state的值,而是使用setState方法來改state的值。
如: // 錯誤示範:直接更改state的值
increment(){
this.state.count = this.state.count + 1
console.log(this.state.count)
}
// 結果導致頁面上的count值并沒有改變,僅僅改了後臺的值(見下面的截圖)
如:// 正確的更改state值的做法,使用setState方法
increment(){
this.setState({
count: this.state.count + 1
})
}
// 結果,頁面上的count值如願改變了 (如下圖)
2)若是同步的console.log()打印出的數值會滯後。所以,需要使用異步打印,setState方法有callback function可以使用。
3)當必须根据以前的state值来更新state时,可以傳入一個函数作为参数,而不是傳入常规的对象。
二、Event Handling
1. 四種綁定this的方法
1)在render中使用bind
如:render() {
return (
<div>
<div>{this.state.message}</div>
<button onClick = {this.clickHandler.bind(this)}>Click</button>
</div>
)
}
2)在render中使用arrow function
如:render() {
return (
<div>
<div>{this.state.message}</div>
<<button onClick = {() => this.clickHandler()}>Click</button>
</div>
)
}
3)直接在類構造器中使用bind方法(比較常用,推薦)
如:this.clickHandler = this.clickHandler.bind(this)
render() {
return (
<div>
<div>{this.state.message}</div>
<button onClick = {this.clickHandler}>Click</button>
</div>
)
}
4)類似添加屬性,在arrow function中綁定(推薦)
如:clickHandler = () => {
this.setState({
message: 'Goodbye.'
})
}
render() {
return (
<div>
<div>{this.state.message}</div>
<button onClick = {this.clickHandler}>Click</button>
</div>
)
}