为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方法的执行是异步的。所以想要获取最新的状态值。需要通过回调函数。

posted @ 2019-11-09 15:31  秋风渡明月  阅读(4942)  评论(0编辑  收藏  举报