React study notes - event processing binding this point

using arrow functions

write code directly

Taking advantage of the fact that the arrow function itself has no scope, use the arrow function to handle this pointing, but this method will create a new function every time it is rendered

class App extends React.Component {
    
    
	constructor(){
    
    
		this.state = {
    
    
			count: 0
		}
	}
	render(){
    
    
		return (
			<span>{
    
    this.state.count}</span>
			<button onClick={
    
    () => {
    
    
				this.setState({
    
    count:this.state.count + 1})
			}}/>
		}
	}
}

Use the arrow function to call the corresponding function

class App extends React.Component {
    
    
	constructor(){
    
    
		this.state = {
    
    
			count: 0
		}
	}
	add(){
    
    
		this.setState({
    
    
			count: this.state.count + 1
		})
	}
	render(){
    
    
		return (
			<span>{
    
    this.state.count}</span>
			<button onClick={
    
    () => {
    
    
				this.add()
			}}/>
		}
	}
}

Use Function.prototype.bind()

React's event handling requires manual binding of this

Show bindings in constructor()

class App extends React.Component {
    
    
	constructor(){
    
    
		this.state = {
    
    
			count: 0
		}
		this.add = this.add.bind(this)
	}
	add(){
    
    
		this.setState({
    
    
			count: this.state.count + 1
		})
	}
	render(){
    
    
		return (
			<span>{
    
    this.state.count}</span>
			<button onClick={
    
    this.add}/>
		}
	}
}

Use bind in element tags

class App extends React.Component {
    
    
	constructor(){
    
    
		this.state = {
    
    
			count: 0
		}
	}
	add(){
    
    
		this.setState({
    
    
			count: this.state.count + 1
		})
	}
	render(){
    
    
		return (
			<span>{
    
    this.state.count}</span>
			<button onClick={
    
    this.add.bind(this)}/>
		}
	}
}

proposal-class-fields

class App extends React.Component {
    
    
	constructor(){
    
    
		this.state = {
    
    
			count: 0
		}
	}
	add = ()=>{
    
    
		this.setState({
    
    
			count: this.state.count + 1
		})
	}
	render(){
    
    
		return (
			<span>{
    
    this.state.count}</span>
			<button onClick={
    
    this.add}/>
		}
	}
}

Guess you like

Origin blog.csdn.net/m0_52761633/article/details/122844401