WEBPACK+ES6+REACT入门6/7-使用this.setState修改state上的数据
步骤
1、components下新建BindEventState.jsx文件,代码如下:
import React from 'react'
export default class BindEventState extends React.Component{
constructor(){
super()
this.state = {}
}
render(){
return <div>
<button onClick={()=>{this.show()}}>按钮</button>
</div>
}
show = ()=>{
console.log('show方法被调用')
}
}
2、做以下修改:
import React from 'react'
export default class BindEventState extends React.Component{
constructor(){
super()
this.state = {}
}
render(){
return <div>
<button onClick={ ()=>this.show() }>按钮</button>
</div>
}
show = ()=>{
console.log('show方法被调用')
}
}
3、为state添加msg
import React from 'react'
export default class BindEventState extends React.Component{
constructor(){
super()
this.state = {
msg:'HAHA'
}
}
render(){
return <div>
<button onClick={ ()=>this.show() }>按钮</button>
<h3>{this.state.msg}</h3>
</div>
}
show = ()=>{
console.log('show方法被调用')
}
}
React中,如果想为state中的数据重新赋值,不可以使用this.state. = 值
应调用React提供的this.setState({msg:‘123’})**
需求:点击按钮,修改msg的值。
import React from 'react'
export default class BindEventState extends React.Component{
constructor(){
super()
this.state = {
msg:'HAHA'
}
}
render(){
return <div>
<button onClick={ ()=>this.show() }>按钮</button>
<h3>{this.state.msg}</h3>
</div>
}
show = ()=>{
console.log('show方法被调用')
//React中,如果想为state中的数据重新赋值,不可以使用this.state.** = 值
//应调用React提供的this.setState({msg:'123'})
//React中,使用this.setState()修改状态值
this.setState({msg:'134'})
}
}
注意项
注意:在setState中,只会把对应的state状态更新,而不会覆盖其他的state状态
注意:this.setState方法为异步。在this.setState之后又想拿到最新的state值,需要使用this.setState({{},callback})
上一篇:WEBPACK+ES6+REACT入门(5/7)-在React中为按钮绑定点击事件
下一篇:WEBPACK+ES6+REACT入门(7/7)-React中绑定文本框与state中的值
END