react-生命週期

表單

  • 經過三種當時獲取表單的數據
  • 包含表單的組件分類
    • 受控組件:表單項輸入數據可以自動收集成狀態,案例中的age字段
    • 非受控組件:須要時才手動讀取表單輸入框中的數據,案例中的username和password字段
  • 大部分推薦使用受控組件,由於其更符合react的思想,不須要進行DOM的操做,並且react也不推薦過多的使用refs
class Login extends React.Component {
    constructor(props){
        super(props)

        this.state = {
            age:18
        }

        this.handleSubmit = this.handleSubmit.bind(this)
        this.handleChange = this.handleChange.bind(this)
    }

    handleSubmit(event){
        event.preventDefault();
        // 經過舊的refs獲取username
        const username = this.refs.username.value
        // 經過新的refs獲取username
        const pwd = this.pwd.value
        // 經過狀態獲取age
        const {age} = this.state

        console.log(username,pwd,age);
    }

    handleChange(event){
        // 因爲原生的onchange事件並非真的在change時觸發事件,而是在失去焦點的時候纔會觸發change事件
        // react在onChange事件作了優化,會在change的時候就觸發事件
        const age = event.target.value
        this.setState({
            age
        })

    }

    render(){
        return (
            <form action="" method="get" onSubmit={this.handleSubmit}>
            <p>
            username: <input type="text" ref="username" />
            </p>
            <p>
            password: <input type="password" ref={input => this.pwd = input} />
            </p>
            <p>
            age: <input type="number" value={this.state.age} onChange={this.handleChange} />
            </p>
            <p>
            <input type="submit" value="login" />
            </p>
            </form>
        )
    }
}


ReactDOM.render(<Login/>,document.getElementById('app'))

組件生命週期

  • 生命週期理解
    • 就是一個組件對象從建立到結束的一個過程,在這個過程組件對象會經歷特定的階段,每一個特定的階段都會對應一個相應的勾子函數
    • 勾子函數本質就是生命週期的回調函數,在組件的生命週期特定時刻進行回調
    • React.Component已經定義好了一系列的勾子函數,如果須要在特定的時間節點作一些事情,能夠重寫特定的勾子函數,在勾子中實現本身的邏輯功能
  • 生命週期
    • 組件有三個生命週期狀態
      • Mount:插入真實DOM,其對應的勾子函數爲:componentWillMount()和componentDidMount()
      • Update:從新渲染,其對應的勾子函數爲:componentWillUpdate()和componentDidMount()
      • Unmount:銷燬真實DOM,其對應的勾子函數爲:componentWillUnmount()
  • 生命週期流程
    • 首次初始化渲染顯示:ReactDOM.render()
      • constructor():建立對象初始化state
      • componentWillMount():將要插入回調
      • render():插入虛擬DOM回調
      • componentDidMount():插入完成回調
    • 每次更新state:this.setState()
      • componentWillUpdate():將要更新回調
      • render():更新、從新渲染
      • componentDidUpdate():更新完成回調
    • 移除組件:ReactDOM.unmountComponentAtNode()
      • componentWillUnmount():組件將要銷燬時的回調
    • 經常使用勾子
      • render():初始化渲染和更新都會調用
      • componentDidMount():開啓監聽、ajax請求等
      • componentWillUnmount():作一些收尾的工做,清除定時器等
  • 案例
  • 實現一個組件
    • 讓文本實現顯示/隱藏動畫
    • 切換時間2s
    • 點擊按鈕 從界面中移除
// 定義組件 
class Life extends React.Component{
    constructor(props){
        super(props)

        this.state = {
            opacity:1,
            color:`#f0f`
        }

        this.cancelTime = this.cancelTime.bind(this)
    }

    componentDidMount(){
        // 定時器做用域問題
        // 1. 經過bind解決
        // 2. 箭頭函數
        this.timer = setInterval( function() {
            let {opacity} = this.state
            opacity -= 0.1

            //不能使用opacity === 0
            // 由於js的計算存在偏差
            if(opacity <= 0){
                opacity = 1
            }
            this.setState({
                opacity
            })

        }.bind(this),200)

    }

    cancelTime(){
        // 移除組件
        ReactDOM.unmountComponentAtNode(document.getElementById('app'))

    }

    componentWillUnmount(){
        // 銷燬組件以前的勾子
        // 定時器必須清除,否則會形成內存泄露的問題
        clearInterval(this.timer)

    }

    render(){
        const {msg} = this.props
        const {...style} = this.state

        return (
            <div>
            <h1 style={style} >{msg}</h1>
            <button onClick={this.cancelTime}>取消定時器</button>
            </div>
        )
    }
}

// 渲染組件
ReactDOM.render(<Life msg="生命週期演示"/>,document.getElementById('app'))
  • 問題javascript

    • 樣式綁定,首先將樣式存在state中,在render中將樣式幫上java

      //方式2:綁定樣式
      // 由於綁定樣式是在js中使用,因此樣式是使用對象的方式傳入
      const {opacity,color} = this.state
      //這裏須要使用雙花括號,由於是在js中綁定樣式,樣式在一個對象中以鍵值對的形式存在
      <h1 style={{opacity,color}} >{msg}</h1>
      
      //方式2:綁定樣式
      // 使用...將樣式以對象的方式取出,能夠直接綁定至樣式上 
      const {...style} = this.state
      <h1 style={style} >{msg}</h1>
    • 定時器必須清除,否則會形成內存泄露的問題react

相關文章
相關標籤/搜索