在实际项目中,一般处理函数的this都会默认指向当前函数,我们需要将this调整为指向其组件实例本身。这里提供几种方法供借鉴。
1.直接在函数中使用this,会出现undefined错误
直接在函数中使用this的话,无法访问到实例的state,会引起报错。
2.三个方法来处理
我们可以从构造函数绑定this、改造成箭头函数和在调用方法处绑定this来实现this正常指向组件实例。
import React, { Component } from 'react';
import {Header} from '../../component'
class Home extends Component {
constructor(props) {
super(props);
this.state = {
msgone:'这是Home组件的第一个栗子',
msgtwo:'这是Home组件的第二个栗子',
msgthree:'这是Home组件的第三个栗子',
}
this.refreshone = this.refreshone.bind(this);
}
//在构造函数中绑定组件的this到函数当中,使this指向组件实例
refreshone(){
this.setState({
msgone:'第1个栗子刷新了!',
})
}
//使用箭头将方法变为匿名调用,使this指向组件实例
refreshtwo =() =>{
this.setState({
msgtwo:'第2个栗子刷新了!',
})
}
//在调用此方法处绑定组件的this(button的点击方法里),使this指向组件实例
refreshthree(){
this.setState({
msgthree:'第3个栗子刷新了!',
})
}
render () {
return (
<div>
<Header/>
首页啊
<h3>{this.state.msgone}</h3>
<button onClick={this.refreshone}>刷新第1个栗子</button>
<h3>{this.state.msgtwo}</h3>
<button onClick={this.refreshtwo}>刷新第2个栗子</button>
<h3>{this.state.msgthree}</h3>
<button onClick={this.refreshthree.bind(this)}>刷新第3个栗子</button>
</div>
)
}
}
export default Home
结果如下。