class Demo extends React.Component{
handle(){
console.log(this)
}
render(){
return (
<div onClick={this.handle}>点击我</div>
)
}
}
- 控制台会显示
undefined
。因为在class中,自定义方法会自动加上局部的use strict
,所以this不能指向window
,值为undefined
。
- 解决class中方法的
this
指向方法一
- 在
constructor
中使用bind
改变this
指向
class Demo extends React.Component{
constructor(props){
super(props)
this.handle = this.handle.bind(this)
}
handle(){
console.log(this)
}
render(){
return (
<div onClick={this.handle}>点击我</div>
)
}
}
- 解决class中方法的
this
指向方法一
- 使用箭头函数
class Demo extends React.Component{
handle = () => {
console.log(this)
}
render(){
return (
<div onClick={this.handle}>点击我</div>
)
}
}