第一种方法
// 导入react
import React from 'react';
import ReactDOM from 'react-dom';
// 创建组件
class APP extends React.Component {
state = {
count: 0
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={() => {
this.setState({
count: this.state.count + 1
})
}}>点击+1</button>
</div>
)
}
}
// 渲染组件
ReactDOM.render(<APP />, document.getElementById('root'))
使用class实例的方法
// 导入react
import React from 'react';
import ReactDOM from 'react-dom';
// 创建组件
class APP extends React.Component {
state = {
count: 0
}
add = () => {
this.setState({
count: this.state.count + 1
}
)
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.add}>点击+1</button>
</div>
)
}
}
// 渲染组件
ReactDOM.render(<APP />, document.getElementById('root'))
第三种 利用constructor改变this指向
// 导入react
import React from 'react';
import ReactDOM from 'react-dom';
// 创建组件
class APP extends React.Component {
state = {
count: 0
}
constructor() {
super()
this.add = this.add.bind(this)
}
add() {
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.add}>点击+1</button>
</div>
)
}
}
// 渲染组件
ReactDOM.render(<APP />, document.getElementById('root'))
state的基本使用