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方法的執行是異步的。所以想要獲取最新的狀態值。需要通過回調函數。