Starting from the onClick event without brackets
import React from 'react'
import './App.css'
class TestComponent extends React.Component {
clickHandler () {
console.log('111')
console.log('this指向:', this)
}
render () {
return (
<button onClick={
this.clickHandler()}>点击我</button>
)
}
}
function App () {
return (
<div>
<TestComponent></TestComponent>
</div>
)
}
export default App
The expected function is that after clicking the button, the console outputs 111 and this point, but in fact, this method will be executed immediately after rendering, and the corresponding information has been output without clicking the button:
This is because in react's jsx syntax, the function of {} is to execute. Adding () to a js expression is equivalent to calling a function, that is, it is this.clickHandler
executed immediately.
What happens if you don’t add ()? Refresh the page, there is no output information, click the button, and the information is output. It seems that the problem has been solved, but at this time you will find that the this point has changed:
Solution
There are three solutions to solve the problem pointed to by this above
1. public class fields (most recommended)
Documentation
Usage: Using an instance method in the form of an arrow function,clickHandler = () => {}
import React from 'react'
import './App.css'
class TestComponent extends React.Component {
clickHandler = () => {
console.log('111')
console.log('this指向:', this)
}
render () {
return (
<button onClick={
this.clickHandler}>点击我</button>
)
}
}
function App () {
return (
<div>
<TestComponent></TestComponent>
</div>
)
}
export default App
2. Arrow functions
Arrow function features:
- The arrow function declaration is assigned to the click event, but it is not executed. It will be executed only after the click is triggered
- The this in the arrow function is actually the this of the outer function
Usage: use arrow function in event binding position,onClick={() => this.clickHandler()}
import React from 'react'
import './App.css'
class TestComponent extends React.Component {
clickHandler () {
console.log('111')
console.log('this指向:', this)
}
render () {
return (
<button onClick={
() => this.clickHandler()}>点击我</button>
)
}
}
function App () {
return (
<div>
<TestComponent></TestComponent>
</div>
)
}
export default App
3. In the constructor, bind this through bind
It is equivalent to modifying the this of the callback function to always point to the current component instance object during the initialization phase of the class component.this.clickHandler = this.clickHandler.bind(this)
import React from 'react'
import './App.css'
class TestComponent extends React.Component {
constructor() {
super()
this.clickHandler = this.clickHandler.bind(this)
}
clickHandler () {
console.log('111')
console.log('this指向:', this)
}
render () {
return (
<button onClick={
this.clickHandler}>点击我</button>
)
}
}
function App () {
return (
<div>
<TestComponent></TestComponent>
</div>
)
}
export default App