案例一:绑定事件,动态渲染
import React, { Component } from 'react'
export default class App extends Component {
constructor(props){
super(props);
this.state = {
num: 1
}
}
render() {
return (
<>
<h2>{this.state.num}</h2>
{}
<button onClick={()=>this.setState({num: this.state.num + 1})}>按钮1 - 累加</button>
{}
<button onClick={this.addNum.bind(this)}>按钮2 - 累加</button>
{}
<button onClick={() =>this.addNum()}>按钮3 - 累加</button>
</>
)
}
addNum(){
this.setState({num: this.state.num + 1})
}
}
案例二:修改样式、传参
.box {
width: 200px;
height: 200px;
background-color:skyblue;
}
import React, { Component } from 'react'
import "./app.css"
export default class App extends Component {
render() {
return (
<div className='box'>
{}
<button onClick={this.btnClick.bind(this, 1)}>按钮1</button>
<button onClick={this.btnClick.bind(this, 2)}>按钮2</button>
<button></button>
</div>
)
}
btnClick(num) {
console.log(num);
}
}