一、在构造器中使用bind绑定this
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.handleAdd = this.handleAdd.bind(this)
}
handleAdd() {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<>
<div>{this.state.count}</div>
<button onClick={this.handleAdd}>+1</button>
{
</>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
二、在回调函数中使用箭头函数
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
handleAdd() {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<>
<div>{this.state.count}</div>
{}
{}
{}
{}
</>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
三、使用类字段语法
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
handleAdd = () => {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<>
<div>{this.state.count}</div>
<button onClick={this.handleAdd}>+1</button>
</>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);