iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

轉職道上的萌芽人生 − 自學程式開發ing系列 第 10

Day 10- 190926學習筆記 ReactJS(中)

React components

  • 可用 Class、Function 兩種方式寫成 component。(W3C建議Class)
  • 命名須以大寫開頭。
  • extends React.Component以獲取內建的methods。
  • render()以回傳欲渲染的HTML。
  • 基本結構如下:
class Classname extends React.Component {
  render() {return <div></div>}
}

props & state

  • component 中的屬性分為兩種型態 props & state
    • state:每個component各自擁有的屬性,可進行控制更改。
    • props:用來與外部溝通的屬性型態,唯讀。
  • state:
    • 每個component用來儲存各自擁有的屬性的object。
    • 用來控制component自身的狀態,每當state變動,則會重新render。
    • this.setState()來執行更改state屬性。
    • state的屬性可在constructor()中進行初始化:
constructor() {
    super()
    this.state = {color: "red"}
}
  • props:
    • component可以接收外部提供的props屬性。
    • 在component中唯讀,無法更改props屬性。
    • 如同HTML的attribute的書寫方式:
      <Classname color="red" />,則其傳入Classname的props的color屬性為red。

React Lifecycle

React有三個階段:Mounting、Updating、Unmounting
https://ithelp.ithome.com.tw/upload/images/20191205/20120981pD0NwevUEx.png
來源

  • Mounting:將 element 放進 DOM 中。此時會照順序啟動4種內建method:
    constructor()getDerivedStateFromProps()render()componentDidMount()
  • Updating:當state、props屬性改變時,進行更新。此時會照順序啟動5種內建method:
    getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()
  • Unmounting:將 element 從 DOM 中移除。只有一個內建method會被啟動:componentWillUnmount()

methods

  • constructor():在最開始啟動,用來做初始化。
  • getDerivedStateFromProps():在render前一刻啟動,可讓props、state屬性,用來將state屬性變更。
  • shouldComponentUpdate():將該component的state屬性設定為可/否更改。
  • render():必要的,每次更新啟動,用來輸出HTML放進DOM。
  • componentDidMount():在render之後啟動。
  • getSnapshotBeforeUpdate():可在屬性更新前啟動,用來記憶更新前的屬性。
  • componentDidUpdate():當DOM的內容被更新時啟動。
  • componentWillUnmount():從DOM中移除前啟動。

官網


上一篇
Day9- 190925學習筆記 ReactJS(上)
下一篇
Day 11- 190927學習筆記 ReactJS(下)
系列文
轉職道上的萌芽人生 − 自學程式開發ing30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言