了解
在react中,分为constructor、return的jsx、方法,前两种的this都是指向当前的组件,而在方
法中this指向undefined,一般会在方法中使用当前组件的属性,需要使用this.xx,所以需要改
变this在方法中的指向
实现的方法
绑定this
使用这种方法时,add函数可以是箭头函数也可以是普通函数
import React,{Component} from 'react'
class App extends Component {
constructor(props){
super(props)
//第二种绑定方法
this.add = this.add.bind(this)
}
state = {number:0}
//箭头函数
add = (event)=>{
console.log(event)
console.log(this)
this.setState({
number:this.state.number+1
})
}
//普通函数
add = function(event){
console.log(this)
console.log(event)
this.setState({
number:this.state.number+1
})
}
render(){
return{
{/* 第一种绑定方法 */}
<button onClick={this.add.bind(this)}></button>
}
}
}
函数必须是箭头函数
import React,{Component} from 'react'
class App extends Component {
state = {number:0}
//箭头函数
add = (event)=>{
console.log(event)
console.log(this)
this.setState({
number:this.state.number+1
})
}
render(){
return{
<button onClick={this.add}></button>
}
}
}
上面的两种方法,在使用时不需要加(),直接把它们当成属性使用,它们在使用时也不可以传参,但是默认会传入event(事件对象)
使用匿名函数
使用的时候,必须加上()进行调用,被调用的函数可以是箭头函数,也可以是普通函数,它的形式是()=>{}
import React,{Component} from 'react'
class App extends Component {
state = {number:0}
//箭头函数
add = (event,payload)=>{
console.log(event)
console.log(this)
this.setState({
number:this.state.number+payload
})
}
//普通函数
add = function(event){
console.log(this)
console.log(event)
this.setState({
number:this.state.number+1
})
}
render(){
return{
<button onClick={(event)=>this.add(event,3)}></button>
<button onClick={(event)=>{this.add(event,3)}}></button>
}
}
}
使用这种形式,可以传参,但是不会默认传入event,需要在调用时直接传,还可以进行传入一个值
上面的两个按钮的区别是,第一个在执行onClick时,它会返回一个add函数,第二个不会返回,直接是调用的