為React綁定事件,並修改state中的值


import React from 'react'

export default  class ClickS extends React.Component {
  constructor () {
    super()
    this.state= {
      msg: '123'
    }
  }
  render () {
    return <div>
      <button onClick={()=>this.show()}>按鈕</button>
      <h2>{this.state.msg}</h2>
    </div>
  }
  show () {
    console.log(this)
    this.setState({
      msg: '222'
    })
  }
}

  

 也可以這么寫

<button onClick={this.show.bind(this)}>按鈕</button>

  

  show () {
    console.log(this)
    this.setState({
      msg: '222'
    }, () => {
      console.log(this.state.msg) // 更新后的值222
    })
    console.log(this.state.msg) // 123
  }

  

 

 

 

 

   注意:

  在React中想為state中的數據重新賦值,不要使用this.state.xxx = 值。應該使用React提供的this.setState({鍵名:值})來進行修改。

  如果this.state有多個值,而只對其中一個進行修改,並不會影響其他的值。應setState只會把對應state狀態值更新,而不會覆蓋其他的state狀態值。

    

 

     

 

 

 

        同時,this.setState方法的執行是異步的。所以想要獲取最新的狀態值。需要通過回調函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM