react 開發
- 本質(虛擬DOM)
- 目的(高效渲染)
認知 (----簡單實例)
- cnpm i react react-dom -s
- 在頁面上引入這兩個包 (react react-dom)
- react 創建組件,組件生命週期等
- react-dom 封裝了和 DOM 操作相關 比如要把組件渲染到頁面
- 使用 JS 創建DOM節點:
- 在 react 中,創建DOM元素,只能使用 react 提供的 js API, 不能直接手寫html
- React.createElement() 方法,用於創建DOM 對象,接收三個及以上的參數
- 參數1.字符串類型的參數,表示創建的元素類型
- 參數2.是一個屬性對象,表示 創建的元素上有哪些屬性
- 參數3(....).表示當前元素的子節點 , 這個參數開始可以在後面放好多的虛擬DOM
var myH1 = React.createElement('h1',null,'這個是h1')
var myDiv = React.createElement('div',{title:'this is a div',id:'myDiv'},'這是一個div',myH1)
4.用 ReactDOM 實例把元素渲染頁面指定的容器中
// ReactDOM.render('要渲染的虛擬DOM元素','要渲染到頁面上的位置')
// ReactDOM.render('要渲染的虛擬DOM元素',document.getElementById('id'))
ReactDOM.render(myDiv,document.getElementById('app'))
生命週期
static defaultProps={}
this.state = {}
創建
ComponentWillMount: 組件將要掛載,
render: 創建虛擬DOM樹,即將掛載到頁面
ComponentDidMount: 掛載完成
運行
ComponentWillReceiveProps: 組件接收 新 的 Props 屬性 只有外界傳遞給子組件的屬性被修改的時候觸發這個鉤子函數
shouldComponentUpdate: 組件是否需要更新
ComponentWillUpdate: 組件要被更新,但還沒更新。
render: 重新創建和渲染DOM樹,把組件最新的state數據更新到 DOM樹
ComponentDidUpdate: 組件更新完成,此時組件的數據是最新的
卸載
ComponentWillUnMount: 組件將要被卸載,但這是還是能正常使用
組件生命週期的執行順序:
Mounting:
constructor()
componentWillMount()
render()
componentDidMount()
Updating:
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
Unmounting:
componentWillUnmount()