1.this指向问题
import { Component } from 'react'
import ReactDom from 'react-dom'
class Com1 extends Component {
constructor () {
super()
this.state = {
num: 100
}
}
hClick () {
// alert(1)
console.log(this)
}
render () {
return (
<div>
<h1>事件绑定</h1>
<button onClick={this.hClick}>绑定事件</button>
</div>
)
}
}
const app = (
<div>
<Com1 />
</div>
)
ReactDom.render(app, document.getElementById('root'))
如图 我在一个类创建的组件中打印了render中的this和绑定事件的this 打印的结果render是指当前实例 绑定事件的this却是undefined 这是什么原因呢
请看demo
此时我如果开启了严格模式 this就指向undefined
2.解决方案
解决方案有如下三种
-
Function.prototype.bind()
-
箭头函数
-
class 的实例方法【推荐】
2.1 bind方法
2.2 箭头函数
2.3class 的实例方法【推荐】
3.三种解决方案完整代码
import { Component } from 'react'
import ReactDom from 'react-dom'
class Com1 extends Component {
constructor () {
super()
this.state = {
num: 100
}
}
hClick1 () {
// alert(1)
console.log('hClick1', this)
}
hClick2 () {
console.log('hClick2', this)
}
hClick3 = () => {
console.log('hClick3', this)
}
render () {
console.log('render', this)
return (
<div>
<h1>事件绑定</h1>
<button onClick={this.hClick1.bind(this)}>bind方法解决</button>
<button
onClick={() => {
this.hClick2()
}}>
回调函数解决
</button>
<button onClick={this.hClick3}>class类方法解决</button>
</div>
)
}
}
const app = (
<div>
<Com1 />
</div>
)
ReactDom.render(app, document.getElementById('root'))