为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'
    })
  }
}

  

   注意:

  在React中想为state中的数据重新赋值,不要使用this.state.xxx = 值。应该使用React提供的this.setState({键名:值})来进行修改。

  如果this.state有多个值,而只对其中一个进行修改,并不会影响其他的值。应setState只会把对应state状态值更新,而不会覆盖其他的state状态值。

    

     

        同时,this.setState方法的执行是异步的。所以想要获取最新的状态值。需要通过回调函数。

猜你喜欢

转载自www.cnblogs.com/js-liqian/p/11826192.html
今日推荐