在react中通過(guò)組件狀態(tài)的改變來(lái)渲染組件樣式 是比較重要模塊揍拆。
舉個(gè)例子哲虾,一個(gè)組件的顯示形態(tài)是可以由它數(shù)據(jù)狀態(tài)和配置參數(shù)決定的芽淡。一個(gè)組件可以擁有自己的狀態(tài)马绝,就像一個(gè)點(diǎn)贊按鈕,可以有“已點(diǎn)贊”和“未點(diǎn)贊”狀態(tài)挣菲,并且可以在這兩種狀態(tài)之間進(jìn)行切換富稻。而,React.js 的 state 就是用來(lái)存儲(chǔ)這種可變化的狀態(tài)的白胀。
代碼:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.css'
class LikeButton extends Component {
constructor () {
super()
this.state = { isLiked: false }
}
handleClickOnLikeButton () {
this.setState({
isLiked: !this.state.isLiked
})
}
render () {
return (
<button onClick={this.handleClickOnLikeButton.bind(this)}>
{this.state.isLiked ? '取消' : '點(diǎn)贊'} ??
</button>
)
}
}
首先看到的是isLiked為false;在點(diǎn)擊時(shí)調(diào)用setState方法椭赋,改變成true重新渲染頁(yè)面。
setState 方法由父類 Component 所提供或杠。當(dāng)我們調(diào)用這個(gè)函數(shù)的時(shí)候纹份,React.js 會(huì)更新組件的狀態(tài) state ,并且重新調(diào)用 render 方法,然后再把 render 方法所渲染的最新的內(nèi)容顯示到頁(yè)面上蔓涧。