React event handling
方法一
class flower extends Component {
// 在react中 状态的的修改是使用setatate()
// setatate是用来改变视图的
constructor(props) {
super(props)
this.state = {
info: '没有改变啊'
}
}
// 事件处理程序直接写在类里面
//修改状态 setstate()
setachang = () => {
this.setState({
info: '按钮成功了'
})
}
render() {
return (
<div>
<button onClick={this.setachang}>按钮</button>
<p>{this.state.info}</p>
</div>
)
}
}
export default flower
1. 事件处理程序我们是直接定义为实例方法
2. 事件处理程序我们建议写成箭头函数 - this指向不改变
修改状态
! 在React中状态的修改只能使用setState()
! setState() 的作用是用来更新视图的
! setState是异步的
setState( obj/function, callback ) 参数是有两个的
! The parameter is the object
this.setState({ info:'hahaha' })
方法二
class flower extends Component {
// 在react中 状态的的修改是使用setatate()
// setatate是用来改变视图的
constructor(props) {
super(props)
this.state = {
info: '没有改变啊'
}
}
setachang=()=>{
this.setState(() => {
return {
info: '哈哈哈哈哈'
}
})
}
render() {
return (
<div>
<button onClick={this.setachang}>按钮</button>
<p>{this.state.info}</p>
</div>
)
}
}
export default flower
The role of the constructor
- Inherit the props of the parent component to this.props through super
- Define state
Modification of state-setState
- setState is the only api provided in React that can change the state
- setState is asynchronous in an event loop
- There are two setState parameters
- The first parameter is used to modify the state, it can be Object/function
- The function must have a return value
- The second parameter is a callback function, which can be said to be a side effect execution caused by data changes
- The first parameter is used to modify the state, it can be Object/function
- In React, the one that can update the view is setState
- The parameter is a method-the method must have a return value, and the return value is an object